使用Webpack进行Angular 2翻译

时间:2016-11-16 15:17:31

标签: angular internationalization webpack

我正在尝试关注internationalization的Angular食谱,但我们使用的是Webpack而不是SystemJS。 在食谱中有以下片段:

function getTranslationsWithSystemJs(file: string) {
  return System.import(file + '!text'); // relies on text plugin
}

它使用SystemJS加载翻译文件。我们应该用什么呢?

2 个答案:

答案 0 :(得分:1)

修改

从webpack 2,您可以使用System.import('./relative/path_to/messages.' + locale + '.xlf'),Webpack将获取该文件,并且将避免扫描明显不匹配的文件。

<强>原始

有(可能)有几种方法可以解决这个问题,但这个方法最适合我:

在我的i18n-providers.js中:

function getTranslationFilesWithWebpack(locale: string) {
    const translationFile = `./assets/locale/messages.${locale}.xlf`;
    return require('' + translationFile)()
}

这将让webpack知道我们在运行时需要文件。接下来,我们需要让webpack知道如何处理文件。

在webpack.config.js中:

    module: {
        rules: [
            /*
             * html, typescript and style rules
             */
            {
                test: /\.xlf/,
                loader: 'promise-loader?es6-promise!raw'
            },
            {
                test: /\.json/,
                loader: 'ignore-loader'
            }
        ]
    }

使用通过管道传递到promise-loader的原始加载器将告诉webpack将我的xlf文件放入一个新的块中,并通过返回一个promise来加载它们,这个promise将在调用require('filename')()时解析为文件内容

注意:

  1. 你必须告诉promise-loader使用哪个承诺库。
  2. 因为我没告诉webpack在require('file')中使用哪个加载器,它会尝试扫描所有文件,并会抱怨它无法加载.json文件。这就是我必须使用ignore loader为json配置规则的原因。
  3. 我希望它有所帮助。

答案 1 :(得分:0)

使用Webpack 2我使用当前配置:

在我的webpack.config.js我设置raw-loader来处理.xlf个文件,这告诉Webpack将文件加载为纯文本。

{
    test: /\.xlf/,
    loader: 'raw-loader'
}

然后在i18n.providers.js我将函数定义如下:

function getTranslationsWithES6Import(locale: string) {
/**
 * System.import in Webpack is an alias of the standard dynamic import()
 * but the latter can't be used because Typescript would complain.
 * @see https://webpack.js.org/guides/code-splitting-import/#dynamic-import
 * @see https://github.com/Microsoft/TypeScript/issues/12364
 *
 * Also the file name must not used backticks and the file extension must be
 * within the function call otherwise Webpack won't know how to load it.
 * @see https://github.com/angular/angular-cli/issues/5285#issuecomment-285059969
 */
return System.import('../assets/locale/messages.' + locale + '.xlf');

}