快速开始

本指南将帮助你快速在 Modern.js 项目中集成国际化功能。

安装插件

i18nextreact-i18nextPeer Dependency,需要手动安装。

版本一致性

@modern-js/plugin-i18n 需要与项目中 @modern-js/app-tools 版本保持一致。

pnpm list @modern-js/app-tools
pnpm add @modern-js/plugin-i18n@<version> i18next react-i18next

基础配置

第一步:注册插件

modern.config.ts 中注册插件:

import { appTools, defineConfig } from '@modern-js/app-tools';
import { i18nPlugin } from '@modern-js/plugin-i18n';

export default defineConfig({
  plugins: [
    appTools(),
    i18nPlugin({
      localeDetection: {
        languages: ['zh', 'en'],
        fallbackLanguage: 'en',
      },
    }),
  ],
});

第二步:创建翻译文件

资源加载

默认情况下,插件本地指定目录下查找翻译资源,在后续章节中我们会介绍更多资源加载方式。

创建 config/public/locales 目录:

config/public/locales/
├── en/
│   └── translation.json
└── zh/
    └── translation.json
// locales/en/translation.json
{
  "welcome": "Welcome to Modern.js"
}
// locales/zh/translation.json
{
  "welcome": "欢迎使用 Modern.js"
}

第三步:配置运行时选项

创建 src/modern.runtime.ts

import { defineRuntimeConfig } from '@modern-js/runtime';
import i18next from 'i18next';

// i18next 默认导出一个全局单例,多个应用共用会互相影响。
// createInstance() 创建独立实例,确保每个应用有独立的语言状态。
const i18nInstance = i18next.createInstance();

export default defineRuntimeConfig({
  i18n: {
    i18nInstance,
  },
});

第四步:在组件中使用

通过 t() 函数返回的语言文案,在调用 changeLanguage 后会自动更新,无需手动刷新。

import { useTranslation } from 'react-i18next';
import { useModernI18n } from '@modern-js/plugin-i18n/runtime';

function App() {
  const { t } = useTranslation();
  const { language, changeLanguage, supportedLanguages } = useModernI18n();

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <p>当前语言:{language}</p>
      {supportedLanguages.map(lang => (
        <button
          key={lang}
          onClick={() => changeLanguage(lang)}
          disabled={lang === language}
        >
          {lang}
        </button>
      ))}
    </div>
  );
}

下一步

根据你的需求选择继续阅读: