Use I18n Plugin in Webpack
Webpack
has a plugin called i18n-webpack-plugin
, which can be used to do simple
translation.
Example
This example is taken from the standard i18n example from webpack repo. You can check the whole source code from here.
In the entry file example.js
, we use console.log
function to output some strings:
console.log(__("Hello World")); //this one has the translation
console.log(__("Missing Text")); //this one is missint the translation.
We define the translations in a json
file based on the language. Here we have a de.json
.
{
"Hello World": "Hallo Welt"
}
What we want is two separated bundle files, each has its own correct strings.
The configuation file we need to use is like this:
var path = require("path");
var I18nPlugin = require("i18n-webpack-plugin");
var languages = {
en: null,
de: require("./de.json") // 1
};
module.exports = Object.keys(languages).map(function(language) {
//2
return {
name: language, //3
entry: "./example", //4
output: {
path: path.join(__dirname, "js"),
filename: language + ".output.js"
},
plugins: [
new I18nPlugin(
languages[language] //5
)
]
};
});
So let me explain it one by one.
- We need a mapping table(
languages
object) to tellwebpack
how to find the translation. For each language’s translation file, we userequire()
to load them; - We use
map
function to generate multiple configuration files for each language in our mapping table. In this case, we haveen
andde
. So we will generate 2 configuration files at the same time forwebpack
to process. This is calledmulti-compiler
feature. - We give each configuration file a name and it will be the same as the language name.
- The
entry
should be the same as we need to use in the normal configuration file. In our case, it should be theexample.js
- We need to specify the
I18nPlugin
we use, along with the options.
Plugin Options
plugins: [
...
new I18nPlugin(languageConfig, optionsObj)
],
This plugin takes 2 arguments.
languageConfig
: this is the translation fileoptionsObj
: which has 3 options:optionsObj.functionName
: the default value is__
, you can change it to other function name.optionsObj.failOnMissing
: the default value isfalse
, which will show a warning message, if the mapping text cannot be found. If set totrue
, the message will be an error message.optionsObj.hideMessage
: the default value isfalse
, which will show the warning/error message. If set totrue
, the message will be hide.
Limitations
There are lots of complex situations regarding translation, which can not be handled by this plugin.
For example, the pluralization issue.
Those can certainly be improved in the future.