i18n 是指软件等的国际化与本地化,这个看似复杂的功能实现起来其实比较简单
这篇文章主要介绍如何在前端的项目中实现 i18n
首先,将语言包弄成 Json 格式的文件,比如:
zh.json
:
{
"home": "主页",
"confirm": "确认",
"cancel": "取消",
"page1": {
"title": "标题1",
"header": "头部1",
"body": "身体1",
"footer": "尾部1"
},
"page2": {
"title": "标题2",
"header": "头部2",
"body": "身体2",
"footer": "尾部2"
},
"map": {
statusMap: {
"success": "成功",
"fail": "失败"
}
}
}
en.json
:
{
"home": "Home",
"confirm": "Confirm",
"cancel": "Cancel",
"page1": {
"title": "title1",
"header": "header1",
"body": "body1",
"footer": "footer1"
},
"page2": {
"title": "title2",
"header": "header2",
"body": "body2",
"footer": "footer2"
},
"map": {
"statusMap": {
"success": "Success",
"fail": "Fail"
}
}
}
接下来是最重要的 i18n.js
:
import DeviceInfo from 'react-native-device-info';
import ZH from './language/zh.json';
import EN from './language/en.json';
const LanguageMap = {
'en': EN,
'zh': ZH
};
/**
* 解析层级对象
* @param value {*} {innerObj: {a: 'xxx', b: 'yyy'}} {{a: 'xxx', b: 'yyy'}}
* @param field innerObj.a a
*/
export const getValue = (value = {}, field = '') => {
if (typeof value !== 'object') {
return value;
}
const fields = field.split('.');
return fields.reduce((preVal, currVal) => {
if (!preVal) return null;
return preVal[currVal];
}, value);
};
const getSystemLanguage = () => DeviceInfo.getDeviceLocale().toLowerCase();
const SystemLanguage = getSystemLanguage();
// 定义你的语言设定
export const CurrentLanguage = EnLanguages.includes(SystemLanguage) ? 'en' : 'id';
export const CurrentTranslationConf = LanguageMap[CurrentLanguage];
export const translate = (path) => {
return getValue(CurrentTranslationConf, path) || path;
};
export const translateMap = (path) => {
const map = getValue(CurrentTranslationConf, path);
if (!map) {
const zhMap = getValue(TranslateMap.zh, path) || {};
return Object.keys(zhMap).reduce((acc, cur) => ({...acc, [cur]: cur}), {});
}
return map;
};
在项目中使用:
import {translate as t, translateMap as tMap} from '../i18n.js';
const statusMap = tMap('map.statusMap');
const title = t('page1.title');
// ...
网友评论