For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guides/advanced-features/international/configuration.md.
  • 简体中文
  • 配置说明

    插件配置分为两个文件,各有职责:

    文件用途
    modern.config.ts插件基础设置,在构建/启动时读取
    src/modern.runtime.tsi18next 初始化选项,在运行时读取
    函数类型只能在运行时配置中设置

    modern.config.ts 在构建时执行,无法序列化函数。SDK 加载函数、自定义检测函数等必须放在 modern.runtime.ts 中。

    配置归属一览

    配置项放在哪里
    localeDetection(语言检测、路径重定向等)modern.config.ts
    backend(资源路径、sdk 声明等)modern.config.ts
    i18nInstancemodern.runtime.ts
    initOptions(fallbackLng、ns 等 i18next 选项)modern.runtime.ts
    backend.sdk 的实际加载函数modern.runtime.ts

    CLI 配置

    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: { ... },
          backend: { ... },
        }),
      ],
    });

    localeDetection 选项

    字段类型默认值说明
    languagesstring[][]支持的语言列表
    fallbackLanguagestring''语言检测失败时的兜底语言
    localePathRedirectbooleanfalse接管 URL 语言前缀的识别、重定向和切换,详见路由集成
    i18nextDetectorbooleanfalse启用 i18next 检测器(Cookie / Header 等)
    detectionLanguageDetectorOptions—i18next 检测器详细配置,见语言检测
    ignoreRedirectRoutesstring[] | Function—跳过重定向的路由,见语言检测
    localeDetectionByEntryRecord<string, ...>—多入口按入口覆盖配置

    示例:

    i18nPlugin({
      localeDetection: {
        localePathRedirect: true,
        i18nextDetector: true,
        languages: ['zh', 'en', 'ja'],
        fallbackLanguage: 'en',
        detection: {
          order: ['path', 'cookie', 'header'],
          lookupCookie: 'i18next',
          caches: ['cookie'],
        },
      },
    });

    backend 选项

    interface BackendOptions {
      // 是否启用后端资源加载
      // 配置了 loadPath/addPath 时自动启用;locales 目录存在时也会自动检测
      enabled?: boolean;
    
      // 决定请求哪个 URL 或本地文件来获取翻译文案,支持 {{lng}} 和 {{ns}} 变量
      // 默认:'/locales/{{lng}}/{{ns}}.json'
      loadPath?: string;
    
      // 缺失翻译的上报路径(可选)
      addPath?: string;
    
      // 启用自定义后端 SDK,实际加载函数在运行时配置中提供
      sdk?: boolean | string;
    
      // 链式后端的缓存策略(同时配置 loadPath 和 sdk 时生效)
      // 'none'                  — 本地文件成功后不再请求自定义后端
      // 'refresh'               — 继续请求自定义后端并更新缓存,不更新页面
      // 'refreshAndUpdateStore' — 继续请求并同步刷新页面文案(默认)
      cacheHitMode?: 'none' | 'refresh' | 'refreshAndUpdateStore';
    
      // 多入口场景下按入口覆盖配置
      backendOptionsByEntry?: Record<string, BaseBackendOptions>;
    }

    sdk 字段说明: 在 modern.config.ts 中设为 true 表示声明启用,实际加载函数在 modern.runtime.ts 的 initOptions.backend.sdk 中提供。详见资源加载 → 自定义后端。

    backend 自动启用规则:

    情况结果
    配置了 loadPath 或 addPath自动启用,无需写 enabled: true
    未配置 backend,但 locales 目录存在且有 JSON 文件自动启用,使用默认 loadPath
    显式设置 enabled: false禁用,不做自动检测

    自动检测的目录位置(按优先级):

    1. {项目根目录}/config/public/locales
    2. server.publicDir 配置的目录下的 locales 子目录

    选择哪种后端?

    场景推荐方式
    翻译文件放在项目本地静态文件后端(配置 loadPath,CSR/SSR 自动切换)
    翻译来自远程 API 或翻译平台自定义后端(配置 sdk: true)
    本地兜底 + 远程实时更新链式后端(同时配置 loadPath 和 sdk)

    详细用法见资源加载。

    运行时配置

    src/modern.runtime.ts
    import { defineRuntimeConfig } from '@modern-js/runtime';
    import i18next from 'i18next';
    
    const i18nInstance = i18next.createInstance();
    
    export default defineRuntimeConfig({
      i18n: {
        i18nInstance, // 可选,建议使用独立实例
        initOptions: {
          fallbackLng: 'en',
          supportedLngs: ['zh', 'en'],
          ns: ['translation'],
          defaultNS: 'translation',
          interpolation: {
            escapeValue: false, // React 已默认转义文本,此处关闭避免重复转义
          },
        },
      },
    });

    i18nInstance 配置

    如果需要使用自定义的 i18n 实例,可以在运行时配置中提供:

    import { defineRuntimeConfig } from '@modern-js/runtime';
    import i18next from 'i18next';
    
    // 创建自定义实例
    const customI18n = i18next.createInstance({
      // 自定义配置
    });
    
    export default defineRuntimeConfig({
      i18n: {
        i18nInstance: customI18n,
      },
    });

    initOptions

    支持所有 i18next 初始化选项,常用选项说明如下:

    字段说明
    fallbackLngi18next 找不到翻译键时回退到哪个语言的资源,支持字符串、数组或映射(回退链)
    supportedLngsi18next 支持的语言列表
    ns命名空间列表,默认 ['translation']
    defaultNS默认命名空间,默认 'translation'
    lng强制指定初始语言(通常不需要,由检测器决定)

    fallbackLng 支持回退链写法,适合区域语言降级的场景:

    initOptions: {
      lng: 'zh-CN',
      fallbackLng: {
        'zh-CN': ['zh', 'en'], // zh-CN 找不到时,先找 zh,再找 en
        default: ['en'],
      },
    },

    自定义后端函数配置

    自定义后端的实际加载函数必须在运行时配置中提供:

    // modern.config.ts:只声明启用
    i18nPlugin({
      backend: { sdk: true },
    });
    
    // modern.runtime.ts:提供实际函数
    import type { I18nSdkLoader } from '@modern-js/plugin-i18n/runtime';
    
    const myLoader: I18nSdkLoader = async options => {
      if (options.lng && options.ns) {
        const res = await fetch(`/api/i18n/${options.lng}/${options.ns}`);
        return res.json();
      }
      return {};
    };
    
    export default defineRuntimeConfig({
      i18n: {
        initOptions: {
          backend: { sdk: myLoader },
        },
      },
    });

    完整用法见资源加载 → 自定义后端。

    多入口配置

    多入口项目可以为每个入口单独覆盖配置,详见高级用法 → 多入口配置。