Use I18n Plugin in Webpack
Webpack has a plugin called i18n-webpack-plugin, which can be used to do simple translation.
When I say simple, it is really simple.
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:
|
|
We define the translations in a json file based on the language. Here we have a de.json.
|
|
What we want is two separated bundle files, each has its own correct strings.
The configuation file we need to use is like this:
|
|
So let me explain it one by one.
- We need a mapping table(
languagesobject) to tellwebpackhow to find the translation. For each language’s translation file, we userequire()to load them; - We use
mapfunction to generate multiple configuration files for each language in our mapping table. In this case, we haveenandde. So we will generate 2 configuration files at the same time forwebpackto process. This is calledmulti-compilerfeature. - We give each configuration file a name and it will be the same as the language name.
- The
entryshould 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
I18nPluginwe use, along with the options.
Plugin Options
|
|
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.
