react国际化化插件react-i18n-auto使用详解
react-i18n-auto专门为中文国际化提供的自动化方案,快速迭代国际化开发,方法如下
安装
npminstallreact-i18n-auto--save-dev
第一步:添加babel插件配置(.babelrc添加方式)
{
"plugins":[
"@babel/plugin-transform-runtime",
"react-i18n-auto",
"..."
]
}
第二步:添加自动化配置i18n.config.js
constgenerator=require('react-i18n-auto/generator')
constpath=require('path')
generator.gen({
excluded:/node_modules|output/,//排除文件选项(默认为:/node_modules/)
src:path.resolve(__dirname,'./code'),//源文件目录(必选)
outputPath:path.resolve(__dirname,'./output'),//国际化配置输出目录(必选)
})
然后运行nodei18n.config.js自动生成配置文件,将localePolyfill.js,localeUtils.js,语言包文件自动生成到outputPath目录下
localePolyfill.js暴露全局方法$AI,$$AI和全局变量LOCALE(语言包),LOCALE_VERSION(语言包版本)
更多配置请移步至react-i18n-autogithub主页
第三步:修改webpack配置,为每一个entry入口添加localePolyfill.js
//webpack.config.js
constpath=require('path')
module.exports={
entry:{
main:[
path.resolve(__dirname,'./output/localePolyfill.js'),
path.resolve(__dirname,'./src/index.js')
],
...
},
第四步:修改当前语言(中文无需加载语言包)
importReactfrom'react'
importen_USfrom'../output/en_US/locale'
importlocaleUtilsfrom'../output/localeUtils'
localeUtils.locale(en_US)
//lolale.js
module.exports={
'I_2gaaanh':'Student',
'I_2aq02r1':'Teacher'
}
第五步:唯一的额外的工作,动态加载语言包时(如果语言包已提前加载则无需此操作)
修改前
//const.js
exportdefaultConst={
SelectOptions:[
{
name:'学生',
value:'student',
},
{
name:'教师',
value:'teacher',
},
]
}
//app.js
importReactfrom'react'
importConstfrom'./const'
exportdefaultclassAppextendsReact.Component{
render(){
return
}
}
由于const为常量,当语言包LOCALE更新时,const并不会得到更新,需要手动调用$AI,类似的情况都需要手动更新
修改后
importReactfrom'react'
importConstfrom'./const'
exportdefaultclassAppextendsReact.Component{
render(){
return
}
}
//编译后的const.js
//所有的中文对应的字段,自动添加$_前缀,值为对应中文的uuidKey
exportdefaultConst={
selectOptions:[{
name:'学生',
$_name:"I_2gaaanh",
value:'student'
},{
name:'教师',
$_name:"I_2aq02r1",
value:'teacher'
}]
};
ps:通过代理getter,或提前加载语言包则可跳过步骤5,具体方法可自行尝试
结束
编译前后代码对照,不污染源码,无痕开发
importReactfrom'react'
exportdefaultclassAppextendsReact.Component{
render(){
return
这是标题
这是内容
importReactfrom'react'
exportdefaultclassAppextendsReact.Component{
render(){
return
{$AI('I_5wtgbv1','这是标题')}
{$AI('I_4ximl4b','这是内容')}
到此这篇关于react国际化化插件react-i18n-auto使用详解的文章就介绍到这了,更多相关reacti18nauto内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!