background
Recently, we need to support at least two languages, English and Chinese. You want to complete the task with minimal change and avoid secondary development as much as possible. After research and practical verification, I have successfully achieved my goal. I write this article to record my realization process.
tool
react-intl
React was used for the company project, so the initial choice was react-intl. This library provides the React component and APIS to format dates, numbers, and strings, as well as some other translation operations. This is already a mature and heavily used open source library.
Use react-intl for internationalization
1. Introduce localProvider into APP and inject internationalization function;
2. Wrap the text to be translated in component with formattedMessage, and the props and state with formattedMessage. FormattedMessage must have both id (unique) and defaultMessage attributes
react-intl-universal
Because the use of react- intL also needs to distinguish whether the copy to be translated exists in the state or props, it is not convenient to use scripts to scan and package the copy in the recognition code. Therefore, another project was investigated, react-Intol-universal, which is much simpler to use.
Using the step
- 1. After the installation is complete, prepare two JSON files.
{
"t1": "View"."t2": "Change"."t3": "Update time: {date}, by"
}
Copy the code
English en. Json:
{
"t1": "view"."t2": "modify"."t3": Update Time: {date}, by
}
Copy the code
- 2. Generate locale and introduce it
import intl from 'react-intl-universal';
import EN from '.. /locale/en.json';
import CH from '.. /locale/zh.json';
const locales = {
en_US: EN,
zh_CN: CH
};
const language = localStorage.getItem('lang_type') | |'zh_CN'; Intl.log ({warningHandler: (MSG, detail) => {// Note that this function is available in the development environment, but there is no console.log(')${msg} ${detail}`);
},
currentLocale: language,
locales
})
Copy the code
- 3. Copy replacement
import intl from 'react-intl-universal';
<button>{intl.get('t1').d('look at')}<button>
<button>{intl.get('t2').d('change')}<button>
<div>{intl.get('t3', {date: '2019-05-24 16:39:25'})}</div> // With parametersCopy the code
The results show
The efficiency of tool
Step 3 Use the plug-in i18N-AST. Other tools use regular matches to replace copywriting in code, and there are always some bugs. However, i18N-AST uses the compiler principle to identify the underlying syntax tree to do the replacement work, and the result is more prepared and greatly saves the workload
Complete example.