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> } }