Quick Start

This guide helps you quickly integrate internationalization into a Modern.js project.

Install the Plugin

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

Basic Configuration

Step 1: Register the Plugin

Register the plugin in 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',
      },
    }),
  ],
});

Step 2: Create Translation Files

Resource loading

By default, the plugin looks for translation resources in the specified local directory. More resource loading methods are covered in later chapters.

Create the config/public/locales directory:

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"
}

Step 3: Configure Runtime Options

创建 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,
  },
});

Step 4: Use It in Components

Text returned by the t() function updates automatically after changeLanguage is called. No manual refresh is required.

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

Next Steps

Choose what to read next based on your needs: