🎉🎉 前端多語言編譯處理解決方案 wp-i18n-plugin
- 基於webpack4 AST分析多語言生成插件, 支持Vue, React, Angular
- 自動管理語言配置, 在編譯期後直接生成多語言拆分, 無需在客戶端從新渲染
- 項目打包後根據配置的多語言數量生成多分具備單一語言的文件. 例如使用zh-cn, en則最後輸出將會有
/dist/zh-cn
/dist/en
複製代碼
👏👏安裝
npm install webpack webpack-cli wp-i18n-plugin --save-dev
複製代碼
⚙ webpack.config.js
const WebpackI18n = require('wp-i18n-plugin'),
path = require('path'),
_ = require('lodash');
let webpackConfig = {
name: '',
mode: 'development' || 'production',
entry: './example/example.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'output.js'
},
plugins: [
new WebpackI18n.Plugin({
sourcePath: './example/lang.json',
languageList: ['zh-cn', 'en'],
useLanguage: 'zh-cn',
autoWriteAble: true,
formatSpace: 2,
showDetail: true,
removeUnUseKeys: true
}),
new WebpackI18n.Spliter({
outputName: './example/async-lang.json',
sourcePath: './example/async-lang.json'
})
]
};
複製代碼
📦webpack多編譯設置(使用node api 或者 webpack config中的一種)
webpackConfigArr = ['zh-cn', 'en'].map(language => {
webpackConfig = _.cloneDeep(webpackConfig);
webpackConfig.name = language;
webpackConfig.output.path = path.join(__dirname, 'dist') + '/' + language;
return webpackConfig;
});
const webpack = require('webpack');
webpack(webpackConfigArr, (err, stats) => {
err && console.log(err);
});
複製代碼
module.exports = ['zh-cn', 'en'].map((language) => {
webpackConfig = _.cloneDeep(webpackConfig);
webpackConfig.name = language;
webpackConfig.output.path = path.join(__dirname, 'dist') + '/' + language;
return webpackConfig;
});
複製代碼
🌰例子
example.js
console.log('__("你好")');
複製代碼
lang.json
{
"你好": {
"zh-cn": "你好",
"en": "Hello"
}
}
複製代碼
🐭example.js編譯後輸出結果:
console.log('Hello');
複製代碼
console.log('你好');
複製代碼
🖖 關於編譯性能提高
- 建議使用在項目中加入cache-loader進行緩存以提升效率
- 建議開發時只啓動單個語言進行開發, 以下降編譯次數以達到快速編譯的效果