logo
  • Guide
  • Config
  • Plugin
  • API
  • Examples
  • Community
  • Modern.js 2.x Docs
  • English
    • 简体中文
    • English
    • Start
      Introduction
      Quick Start
      Upgrading
      Glossary
      Tech Stack
      Core Concept
      Page Entry
      Build Engine
      Web Server
      Basic Features
      Routes
      Routing
      Config Routes
      Data Solution
      Data Fetching
      Data Writing
      Data Caching
      Rendering
      Rendering Mode Overview
      Server-Side Rendering
      Streaming Server-Side Rendering
      Rendering Cache
      Static Site Generation
      React Server Components (RSC)
      Render Preprocessing
      Styling
      Styling
      Use CSS Modules
      Using CSS-in-JS
      Using Tailwind CSS
      HTML Template
      Import Static Assets
      Import JSON Files
      Import SVG Assets
      Import Wasm Assets
      Debug
      Data Mocking
      Network Proxy
      Using Rsdoctor
      Using Storybook
      Testing
      Playwright
      Vitest
      Jest
      Cypress
      Path Alias
      Environment Variables
      Output Files
      Deploy Application
      Advanced Features
      Using Rspack
      Using BFF
      Basic Usage
      Runtime Framework
      Creating Extensible BFF Functions
      Extend BFF Server
      Extend Request SDK
      File Upload
      Cross-Project Invocation
      Optimize Page Performance
      Code Splitting
      Inline Static Assets
      Bundle Size Optimization
      React Compiler
      Improve Build Performance
      Browser Compatibility
      Low-Level Tools
      Source Code Build Mode
      Server Monitor
      Monitors
      Logs Events
      Metrics Events
      Internationalization
      Basic Concepts
      Quick Start
      Configuration
      Locale Detection
      Resource Loading
      Routing Integration
      API Reference
      Advanced Usage
      Best Practices
      Custom Web Server
      Topic Detail
      Module Federation
      Introduction
      Getting Started
      Application-Level Modules
      Server-Side Rendering
      Deployment
      Integrating Internationalization
      FAQ
      Dependencies FAQ
      CLI FAQ
      Build FAQ
      HMR FAQ
      Upgrade
      Overview
      Configuration Changes
      Entry Changes
      Custom Web Server Changes
      Tailwind Plugin Changes
      Other Important Changes
      📝 Edit this page
      Previous pageBasic ConceptsNext pageConfiguration

      #Quick Start

      This guide will help you quickly integrate internationalization functionality into your Modern.js project.

      #Install Plugin

      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
      Info

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

      #Basic Configuration

      #Configure Plugin in modern.config.ts

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

      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.

      #Configure Runtime Options in 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 实例。

      #Create Language Resource Files

      Create a locales folder in the project root and organize resource files by language:

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

      #Use in Components

      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;

      #Next Steps

      • Learn detailed Configuration instructions
      • Learn about multiple Locale Detection methods
      • Check Resource Loading configuration options