AiI18nOptions

从 @ai-i18n/vite 导入:

import type { AiI18nOptions } from '@ai-i18n/vite';

最小配置

通常只需提供源语言与语言列表。框架自动检测,类型声明和 HTML 显式翻译表达式提取默认开启, 成功 Build 会输出覆盖率;自动导入、持久化、语言分包和 Provider 调用均需按需启用。

aiI18n({
  sourceLang: 'zh-CN',
  locales: [
    { value: 'zh-CN', label: '中文' },
    { value: 'en-US', label: 'English' },
  ],
});

定义

interface AiI18nOptions {
  framework?: AiI18nFramework;
  autoImport?: boolean;
  dts?: string | false;
  sourceLang: string;
  defaultLang?: string;
  locales: readonly LangOption[];
  persist?: boolean | AiI18nPersistOptions;
  loading?: boolean | AiI18nLocaleLoadingOptions;
  translationMemory?: AiI18nTranslationMemoryOptions;
  provider?: AiI18nProviderOptions;
  failOnMissingTranslations?: boolean;
  directory?: string;
  cleanup?: AiI18nCleanupOptions;
  diagnostics?: AiI18nDiagnosticsOptions;
  html?: boolean | HtmlExtractorOptions;
}

常用配置

字段类型必填默认值作用
sourceLangstring是无源码文案所属语言。
localesreadonly LangOption[]是无项目支持的语言列表。
defaultLangstring否sourceLang没有有效持久化值时使用的初始语言。
autoImportboolean否false自动注入当前框架模式的 Runtime API。
persistboolean 或 AiI18nPersistOptions否false使用 localStorage 保存语言偏好。
loadingboolean | AiI18nLocaleLoadingOptions否false,全语言注册按 locale 拆分语言资产。
providerAiI18nProviderOptions否不调用模型配置自动翻译函数、缓存与调度策略。

高级配置

以下选项通常无需修改;仅在文件布局、发布检查、历史清理或排障时调整。

字段类型必填默认值作用
frameworkAiI18nFramework否自动检测指定 Vanilla、Vue 或 React 模式。
dtsstring | false否'src/ai-i18n.d.ts'设置声明文件路径,或关闭生成。
directorystring否'i18n'设置协议目录;相对路径基于 Vite root。
htmlboolean | HtmlExtractorOptions否true默认提取 HTML 显式翻译表达式。
failOnMissingTranslationsboolean否false构建时若目标语言仍有缺译,则构建失败。
translationMemoryAiI18nTranslationMemoryOptions否分片 JSON配置可选个人候选缓存,并按需限制历史译文容量。
cleanupAiI18nCleanupOptions否保留默认清理策略控制失效提取文件和孤立消息的清理。
diagnosticsAiI18nDiagnosticsOptions否构建汇总开,其余关闭配置构建汇总、Dev 慢日志和性能报告。

语言约束

locales 至少包含一项,且每一项的 value 必须唯一。sourceLang 与 defaultLang 必须匹配 某个 value。

目标语言缺译或值为 null 时,Runtime 返回 source 文案。插件不会为 sourceLang 生成重复的 目标语言文件。

开启 failOnMissingTranslations 后,Build 会等待本轮自动翻译并检查入口可达文案。任一目标语言 仍缺译时,构建报错并显示各语言的缺译数量;不配置 Provider 也可使用。Dev 不受影响, diagnostics.buildSummary: false 也不会关闭检查。空字符串和有效人工覆盖均视为已翻译。

初始语言按以下顺序选择:

  1. localStorage 中有效的持久化值;
  2. defaultLang;
  3. 省略 defaultLang 时使用 sourceLang。

框架与自动导入

省略 framework 时,插件读取 Vite 最终插件列表:

检测结果模式
存在 vite:vue 或 vite:vue-jsxvue
存在 vite:react*react
都不存在vanilla

同一个 build 同时出现 Vue 与 React 插件时会报错。显式设置 framework 不会绕过这项检查。 显式值只能是 'vanilla'、'vue' 或 'react';JavaScript 配置中的其他值也会在启动时被拒绝。

autoImport: true 注入的 API 取决于最终模式。三种模式都有 t、setLang、getLang、 getLangs、getLangLoadState 与 subscribe;Vue 额外注入 useI18n、tRef、 i18nComputed、tComputed,React 额外注入 useI18n。

完整接入方法见自动导入。

路径

directory 与 dts 的相对路径都基于 Vite root 解析;传入绝对路径时直接使用该路径。

翻译校对

翻译校对不属于 AiI18nOptions。需要时从 @ai-i18n/vite/review 导入并在 Vite plugins 中注册 aiI18nReview();省略该插件时不提供校对入口或独立校对页。详见翻译校对。

相关内容