最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
react国际化插件react-i18n-auto使用代码解析
时间:2020-03-31 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下react国际化插件react-i18n-auto使用代码解析,文中代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
react-i18n-auto专门为中文国际化提供的自动化方案,快速迭代国际化开发,方法如下:
安装
npm install react-i18n-auto --save-dev
第一步:添加babel插件配置(.babelrc添加方式)
{ "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目录下
localePolyfill.js暴露全局方法 $AI, $$AI 和全局变量 LOCALE (语言包),LOCALE_VERSION (语言包版本)
更多配置请移步至react-i18n-auto github主页
第三步:修改webpack配置,为每一个entry入口添加localePolyfill.js
// webpack.config.js 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 en_US from '../output/en_US/locale' import localeUtils from '../output/localeUtils' localeUtils.locale(en_US) // lolale.js module.exports = { 'I_2gaaanh': 'Student', 'I_2aq02r1': 'Teacher' }
第五步:唯一的额外的工作,动态加载语言包时(如果语言包已提前加载则无需此操作)
修改前
// 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.Component { render () { return } }
由于const为常量,当语言包LOCALE更新时,const并不会得到更新,需要手动调用$AI,类似的情况都需要手动更新
修改后
import React from 'react' import Const from './const' export default class App extends React.Component { render () { return } }
// 编译后的const.js // 所有的中文对应的字段,自动添加$_前缀,值为对应中文的uuidKey export default Const = { selectOptions: [{ name: '学生', $_name: "I_2gaaanh", value: 'student' }, { name: '教师', $_name: "I_2aq02r1", value: 'teacher' }] };
ps :通过代理getter,或提前加载语言包则可跳过步骤5,具体方法可自行尝试
结束
编译前后代码对照,不污染源码,无痕开发
import React from 'react' export default class App extends React.Component { render () { return} }这是标题 这是内容
import React from 'react' export default class App extends React.Component { render () { return} }{$AI('I_5wtgbv1', '这是标题')} {$AI('I_4ximl4b', '这是内容')}
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10