快速开始

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

安装插件

首先,安装必要的依赖:

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
Info

i18nextreact-i18next 是 peer dependencies,需要手动安装。

基础配置

modern.config.ts 中注册插件

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

export default defineConfig({
  server: {
    publicDir: './locales', // 必需:指定资源文件目录
  },
  plugins: [
    appTools(),
    i18nPlugin({
      localeDetection: {
        languages: ['zh', 'en'], // 支持的语言列表
        fallbackLanguage: 'en', // 默认语言
      },
      backend: {
        enabled: true, // 启用后端资源加载
        // loadPath 默认为 '/locales/{{lng}}/{{ns}}.json',通常无需修改
        // 注意:你也可以省略 'enabled',只需配置 'loadPath' 或 'addPath',
        // 或者完全省略 backend 配置,让插件自动检测 locales 目录
      },
    }),
  ],
});
Info

server.publicDir 是必需配置,用于指定资源文件的实际存放位置。即使使用默认的 loadPath 路径,也需要配置此项。

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'],
    },
  },
});
Info

modern.runtime.ts 是运行时配置文件,用于配置 i18next 的初始化选项。即使是最基础的配置,也建议创建此文件以确保插件正常工作。

建议使用 i18next.createInstance() 创建一个新的实例,而不是直接使用默认导出的 i18next,这样可以避免全局状态污染,并确保每个应用都有独立的 i18n 实例。

创建语言资源文件

在项目根目录创建 locales 文件夹,并按语言组织资源文件:

locales/
├── en/
│   └── translation.json
└── zh/
    └── translation.json

locales/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>当前语言: {language}</p>
      <div>
        {supportedLanguages.map(lang => (
          <button
            key={lang}
            onClick={() => changeLanguage(lang)}
            disabled={lang === language}
          >
            {lang}
          </button>
        ))}
      </div>
    </div>
  );
}

export default App;

下一步