十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
react-i18n-auto專門為中文國際化提供的自動化方案,快速迭代國際化開發(fā),方法如下
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),華亭企業(yè)網(wǎng)站建設(shè),華亭品牌網(wǎng)站建設(shè),網(wǎng)站定制,華亭網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,華亭網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
安裝
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' }
第五步:唯一的額外的工作,動態(tài)加載語言包時(如果語言包已提前加載則無需此操作)
修改前
// 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并不會得到更新,需要手動調(diào)用$AI,類似的情況都需要手動更新
修改后
import React from 'react' import Const from './const' export default class App extends React.Component { render () { return } }
// 編譯后的const.js // 所有的中文對應(yīng)的字段,自動添加$_前綴,值為對應(yīng)中文的uuidKey export default Const = { selectOptions: [{ name: '學生', $_name: "I_2gaaanh", value: 'student' }, { name: '教師', $_name: "I_2aq02r1", value: 'teacher' }] };
ps :通過代理getter,或提前加載語言包則可跳過步驟5,具體方法可自行嘗試
結(jié)束
編譯前后代碼對照,不污染源碼,無痕開發(fā)
import React from 'react' export default class App extends React.Component { render () { return} }這是標題 這是內(nèi)容
import React from 'react' export default class App extends React.Component { render () { return} }{$AI('I_5wtgbv1', '這是標題')} {$AI('I_4ximl4b', '這是內(nèi)容')}
到此這篇關(guān)于react國際化化插件react-i18n-auto使用詳解的文章就介紹到這了,更多相關(guān)react i18n auto 內(nèi)容請搜索創(chuàng)新互聯(lián)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持創(chuàng)新互聯(lián)!