下载next-i18next依赖,配置NextJS国际化。
npm install i18next --save
1.根文件配置next-i18next.config.js
const languagesConfig = [
{
label: 'English',
value: 'EN',
},
{
label: '中文',
value: 'ZH_CN',
},
];
const i18n = {
defaultLocale: 'EN',
locales: languagesConfig.map((language) => language.value),
};
module.exports = {
i18n,
languagesConfig,
};
2.根文件配置next.config.js
const { i18n } = require('./next-i18next.config.js');
const nextConfig = {
i18n,
};
module.exports = nextConfig;
3.创建类型文件i18n.d.ts,约束TS的类型,resources对应的key是我们在语言文件夹创建的JSON数据。
import commonJSON from './public/locales/EN/common.json';
import searchResultJSON from './public/locales/EN/searchResult.json';
declare module 'react-i18next' {
interface CustomTypeOptions {
resources: {
common: typeof commonJSON;
searchResult: typeof searchResultJSON;
};
}
}
4.在public文件夹中创建locales,文件夹的名称对应上述的languagesConfig的value,然后在各个语言文件夹创建key-value的JSON数据。

image.png
5.代码中使用,因为我们已经配置过TS类型约束,所以代码中会自动提示我们定义好的JSON文件名,以及文件的key值。
import { useTranslation } from 'next-i18next';
const { t } = useTranslation('searchResult'); //key则是我们所创建的JSON文件的名称
t("addToCart") //读取不同语言环境下的value
6.切换多语言
const router = useRouter();
const handleLocaleChange = (event: any) => {
const value = event.target.value;
router.push(router.route, router.asPath, {
locale: value,
});
};