之前在 静态页面多语言的实现 中基本实现了 Webpack 打包完成之后,读取 HTML 文件进行翻译文本的替换,虽然功能上实现了,但是不能预览翻译后的 HTML,因此需要拓展 html-webpack-plugin 插件来实现预览的功能。
思路
Hook html-webpack-plugin 插件,在插件处理 HTML 之前,将对应的文本替换成翻译后的文本即可。
compiler.hooks.compilation.tap('GettextHtmlPlugin', compilation => {
compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tap('GettextHtmlPlugin', data => {
data.html = data.html.replace(/{{*}}/, '')
})
})
gettext-html-plugin
安装
npm install gettext-html-plugin --save-dev
使用
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const GettextHtmlPlugin = require('gettext-html-plugin')
module.exports = {
entry: {
index: 'index.js'
},
output: {
path: __dirname + '/dist',
filename: 'index.js'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: __dirname + '/index.html',
chunks: ['index']
}),
new HtmlWebpackPlugin({
filename: 'zh-cn.html',
template: __dirname + '/index.html',
chunks: ['index']
}),
new GettextHtmlPlugin({
langsPath: __dirname + '/langs',
sources: {
'zh-cn.html': 'zh_CN'
}
})
]
}
参数
名称
类型
默认值
描述
prefix
{String}
{{
翻译文本的前标识符
suffix
{String}
}}
翻译文本的后标识符
langsPath
{String}
null
翻译文本绝对路径
injectLang
{Boolean}
true
是否修改 HTML 中 lang 属性,是否在 body 中插入语言 class
regenerateLangFile
{Boolean}
true
自动重新生成相应的语言文件
sources
{Object}
{}
目标 HTML 文件和语言之间的对应关系