react-i18n-auto专门为中文国际化提供的自动化方案,快速迭代国际化开发,方法以下node
npm install react-i18n-auto --save-dev
react
{ "plugins": [ "@babel/plugin-transform-runtime", "react-i18n-auto", "..." ] }
i18n.config.js
const generator = require('react-i18n-auto/generator') const path = require('path') generator.gen({ excluded: /node_modules|output/, //排除文件选项(默认为:/node_modules/) src: path.resolve(__dirname, './code'), //源文件目录(必选) outputPath: path.resolve(__dirname, './output'), //国际化配置输出目录(必选) })
而后运行 node i18n.config.js
自动生成配置文件,将localePolyfill.js
,localeUtils.js
,语言包文件自动生成到outputPath
目录下webpack
localePolyfill.js
暴露全局方法 $AI
, $$AI
和全局变量 LOCALE
(语言包),LOCALE_VERSION
(语言包版本)git
更多配置请移步至react-i18n-auto github主页github
webpack.config.jsweb
const path = require('path') module.exports = { entry: { main: [ path.resolve(__dirname, './output/localePolyfill.js'), path.resolve(__dirname, './src/index.js') ], ... },
import React from 'react' import zh_CN from '../output/zh_CN' import localeUtils from '../output/localeUtils' localeUtils.locale(zh_CN)
修改前 npm
// const.js export default Const = { SelectOptions:[ { name:'学生', value:'student', }, { name:'教师', value:'teacher', }, ] }
// app.js import React from 'react' import Const from './const' export default class App extends React.Comment { render () { return <select> { Const.selectOptions.map(item => { return <option key={item.value} value={item.value}> {item.name} </option> }) } </select> } }
因为const为常量,当语言包LOCALE
更新时,const并不会获得更新,须要手动调用$AI
,相似的状况都须要手动更新babel
修改后app
import React from 'react' import Const from './const' export default class App extends React.Comment { render () { return <select> { Const.selectOptions.map(item => { return <option key={item.value} value={item.value}> {$AI(item.$_name, item.name)} {/*惟一须要修改的地方*/} </option> }) } </select> } }
// 编译后的const.js // 全部的中文对应的字段,自动添加$_前缀,值为对应中文的uuidKey export default Const = { SelectOptions: [{ name: '学生', $_name: "I_2gaaanh", value: 'student' }, { name: '教师', $_name: "I_2aq02r1", value: 'teacher' }] };
ps :经过代理getter,或提早加载语言包则可跳过步骤5,具体方法可自行尝试
编译先后代码对照,不污染源码,无痕开发ui
import React from 'react' export default class App extends React.Comment { render () { return <div> <header>这是标题</header> <div title='这是提示文字'> <p>这是内容</p> </div> <footer>{this.state.title}</footer> </div> } }
import React from 'react' export default class App extends React.Comment { render () { return <div> <header>{$AI('I_5wtgbv1', '这是标题')}</header> <div title={$AI('I_7reuhi4', '这是提示文字')}> <p>{$AI('I_4ximl4b', '这是内容')}</p> </div> <footer>{this.state.title}</footer> </div> } }