This guide will help you quickly integrate internationalization functionality into your Modern.js project.
First, install the necessary dependencies:
pnpm add @modern-js/plugin-i18n i18next react-i18next
请确保 @modern-js/plugin-i18n 的版本与项目中 @modern-js/app-tools 的版本一致。所有 Modern.js 官方包都使用统一的版本号发布,版本不匹配可能会导致兼容性问题。
请先检查 @modern-js/app-tools 的版本,然后安装相同版本的 @modern-js/plugin-i18n:
# 检查当前 @modern-js/app-tools 的版本
pnpm list @modern-js/app-tools
# 安装相同版本的 @modern-js/plugin-i18n
pnpm add @modern-js/plugin-i18n@<version> i18next react-i18next
i18next 和 react-i18next 是 peer dependencies,需要手动安装。
modern.config.tsimport { appTools, defineConfig } from '@modern-js/app-tools';
import { i18nPlugin } from '@modern-js/plugin-i18n';
export default defineConfig({
server: {
publicDir: './locales', // Required: specify the resource file directory
},
plugins: [
appTools(),
i18nPlugin({
localeDetection: {
languages: ['zh', 'en'], // Supported language list
fallbackLanguage: 'en', // Default language
},
backend: {
enabled: true, // Enable backend resource loading
// loadPath defaults to '/locales/{{lng}}/{{ns}}.json', usually no need to modify
// Note: You can also omit 'enabled' and just configure 'loadPath' or 'addPath',
// or omit backend config entirely to let the plugin auto-detect locales directory
},
}),
],
});
server.publicDir is a required configuration used to specify the actual location of resource files. Even when using the default loadPath, this configuration is still required.
src/modern.runtime.ts创建 src/modern.runtime.ts 文件并配置 i18n 运行时选项:
import { defineRuntimeConfig } from '@modern-js/runtime';
import i18next from 'i18next';
// 建议创建一个新的 i18next 实例,避免使用全局默认实例
const i18nInstance = i18next.createInstance();
export default defineRuntimeConfig({
i18n: {
i18nInstance: i18nInstance,
initOptions: {
fallbackLng: 'en',
supportedLngs: ['zh', 'en'],
},
},
});
modern.runtime.ts 是运行时配置文件,用于配置 i18next 的初始化选项。即使是最基础的配置,也建议创建此文件以确保插件正常工作。
建议使用 i18next.createInstance() 创建一个新的实例,而不是直接使用默认导出的 i18next,这样可以避免全局状态污染,并确保每个应用都有独立的 i18n 实例。
Create a locales folder in the project root and organize resource files by language:
locales/
├── en/
│ └── translation.json
└── zh/
└── translation.jsonlocales/en/translation.json:
{
"hello": "Hello",
"world": "World",
"welcome": "Welcome to Modern.js"
}locales/zh/translation.json:
{
"hello": "你好",
"world": "世界",
"welcome": "欢迎使用 Modern.js"
}import { useModernI18n } from '@modern-js/plugin-i18n/runtime';
import { useTranslation } from 'react-i18next';
function App() {
const { language, changeLanguage, supportedLanguages } = useModernI18n();
const { t } = useTranslation();
return (
<div>
<h1>{t('welcome')}</h1>
<p>Current language: {language}</p>
<div>
{supportedLanguages.map(lang => (
<button
key={lang}
onClick={() => changeLanguage(lang)}
disabled={lang === language}
>
{lang}
</button>
))}
</div>
</div>
);
}
export default App;