文件目录如下:
-
app\assets\locales里面放国际化相关资源
-
l10n.config.js 是配置文件
-
app\assets\locales\resource.js 是工具类
├── l10n.config.js ├── node_modules ├── package.json └── app ├── index.html ├── index.js ├── assets |——locales ├── cn.js |—— en.js ├── en-US.js |—— zh-CN.js |—— resource.js
安装react-intl
en-US.js
import antdEn from "antd/lib/locale-provider/en_US";
import { addLocaleData } from "react-intl";
import en from "react-intl/locale-data/en";
import enMessages from "./en.js";
addLocaleData(en); // 引入多语言环境的数据
export default {
messages: {
...enMessages
},
antd: antdEn,
locale: "en-US",
data: en
};
en.js
export default {
flowpeople: "flowpeople",
forepeople: "forepeople",
houseowner: "houseowner",
specialpeople: "specialpeople",
highriskpeople: "highriskpeople"
};
zh-CN.js
import antdCn from "antd/lib/locale-provider/zh_CN";
import zh from "react-intl/locale-data/zh";
import { addLocaleData } from "react-intl";
import cnMessages from "./cn.js";
// [React Intl] Missing locale data for locale: "zh". Using default locale: "en" as fallback.
addLocaleData(zh);
export default {
messages: {
...cnMessages
},
antd: antdCn,
locale: "zh-cn",
data: zh
};
cn.js
export default {
flowpeople: "境内人口",
forepeople: "境外人员",
houseowner: "房东管理",
specialpeople: "特殊关注人员",
highriskpeople: "高危人员"
};
在 package.json 里面的 scripts 加一条
"trans": "atool-l10n",
运行
npm run trans
生成l10n.config.js文件,并不是那么的好用,我们还要做些修改
具体的参数看这里ant-tool/atool-l10n
l10n.config.js
module.exports = {
middlewares: {
summary: ["summary?sourcePattern=build/messages/**/*.json"],
process: [
"fetchLocal?source=locales,skip",
"metaToResult?from=defaultMessage,to=en",
"youdao?apiname=YourName,apikey=YourKey",
"reduce?-autoPick,autoReduce[]=local,autoReduce[]=meta"
],
emit: ["save?dest=app/assets/locales"]
}
};
index.js
import { LocaleProvider } from "antd";
import { IntlProvider } from "react-intl";
import zhCN from "./assets/locales/zh-CN";
import enUS from "./assets/locales/en-US";
const getCurrentAppLocale = () => {
//动态切换的话将语言参数存入session中,重载页面
// const language = store.get("language_key");
// const language = window.navigator.language;
const language = "zh-CN";
switch (language) {
case "zh-CN":
return zhCN;
default:
return enUS;
}
};
window.appLocale = getCurrentAppLocale();
render(
<IntlProvider
key={window.appLocale.locale}
locale={window.appLocale.locale}
messages={window.appLocale.messages}
formats={window.appLocale.formats}
>
<LocaleProvider locale={window.appLocale.antd}>
<Provider store={store}>
<Routes />
</Provider>
</LocaleProvider>
</IntlProvider>,
document.getElementById("content")
);
resource.js
import React from "react";
import { FormattedMessage } from "react-intl";
export function resource(msgID) {
return <FormattedMessage id={msgID} />;
}
使用
//注意路径
import { resource } from "../../../assets/locales/resource";
<span>{resource("specialpeople")}</span>