搭建环境
- 执行命令:
npx create-react-app my-app --typescript - 进入项目文件夹:
cd my-app - run:
yarn start
多语言配置
react有几个比较成熟的多语言库, 如 react-i18next、 react-intl、 react-intl-universal
react-i18next
官网:react.i18next.com/guides/quic…
- 下载依赖
npm install react-i18next i18next --save
yarn add react-i18next i18next
- 编辑多语言文件, 文件夹
locale
导入系统: 在src/idnex.tsx加入 import './locale'; 即可。
- 编辑自动注入规则:
locale/index.ts
在 index.ts 中, 编辑一个方法, 可以自动扫描
locale下所有的文件夹下的文件, 生成对应的语言包。 若后期需要增加多语言, 只需要在模块下新增语言文件即可,其他地方无需改动。
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
interface ILngProps {
[lng: string]: any
}
const cache: ILngProps = {};
function importAll(r: any) {
// 处理 key
r.keys().forEach((key: any) => {
let lastPoint = key.lastIndexOf('.')
let lastLevel = key.lastIndexOf('/')
let firstLevel = key.indexOf('/')
let index = key.substring(lastLevel + 1, lastPoint)
let name = key.substring(firstLevel + 1, lastLevel)
cache[index] = { [name]: r(key).default, ...cache[index] }
});
const resources: ILngProps = {}
for(let key in cache) {
resources[key] = {translation: { ...cache[key] }}
}
return resources
}
// 获取文件夹
const getFolders = () => {
return importAll(require.context(__dirname, true, /^(\.\/)([a-zA-Z0-9_-])+(\/)([a-zA-Z0-9]+)(\.ts)/))
}
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources: getFolders(), // 语言包资源
lng: "zh", // 当前使用的语言
interpolation: {
escapeValue: false
}
});
export default i18n;
如果
__dirname输出是/, 则修改webpack.config.js的node
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
__dirname: true
},
- 语言包示例
// login/en.ts
const en = {
login: 'login',
register: 'register'
}
export default en;
// login/zh.ts
const zh = {
login: '登录',
register: '注册'
}
export default zh;
- 使用示例
// hook 函数组件
import { useTranslation } from 'react-i18next';
function App () {
const { t } = useTranslation();
return <h1>{t('login.login')}</h1>
}
export default App;
// hoc 组件
import React, { Component } from "react";
import { Translation } from 'react-i18next';
import styles from './index.module.css'
class StyleModule extends Component<{}, {}> {
render() {
return <Translation>
{
t => <div className={styles.test}>
<div>{t('login.login')}</div>
</div>
}
</Translation>
}
}
export default StyleModule;
- 语言切换
i18n.changeLanguage('zh')