使用 AI 提取 i18n 键

将现有的 React 应用转换为多语言支持,通常需要查找硬编码字符串并将其替换为翻译键,这一过程有时较为繁琐。

Lingo.dev CLI 可与 Cursor、GitHub Copilot 等 AI 驱动的 IDE 无缝协作,自动从 React 组件中提取可翻译内容。

下文介绍的概念适用于任何技术栈。为便于说明,这里以 hello world React 应用为例进行演示。

前置条件

在提取键之前,请先在 React 应用中完成基础国际化设置。完整的设置说明请参见 react-intl 文档

按照你的技术栈完成国际化设置后,项目应具备:

  • 应用内可动态切换语言
  • 用于组织翻译文件的基础项目结构

设置流程

安装并配置 Lingo.dev CLI:

npx lingo.dev@latest init

创建空的源文件:

mkdir -p src/locales
echo '{}' > src/locales/en.json

配置 i18n.json:

{
  "locale": {
    "source": "en",
    "targets": ["es", "fr", "de"]
  },
  "buckets": {
    "json": {
      "include": ["src/locales/[locale].json"]
    }
  }
}

使用 AI 提取键

选择你的 React 组件,并使用 AI IDE 提取硬编码字符串:

提取前:

function WelcomeCard() {
  return (
    <div className="card">
      <h2>Welcome to our platform</h2>
      <p>Start your journey with us today</p>
      <button>Get started</button>
    </div>
  );
}

提取要求:

  1. 用 react-intl 的 hooks 和组件替换硬编码字符串
  2. 变量和复数使用 ICU 格式化
  3. 按组件结构分层组织键
  4. 将所有键添加到源 JSON 文件中
  5. 保持命名规范一致

AI 提示词:

Extract all hardcoded strings from React components and:

1. Replace with react-intl:
   - Use useIntl hook for dynamic strings
   - Use FormattedMessage for static text
   - Add ICU formatting for variables ({name}) and plurals ({count})

2. Structure translation keys:
   - Group by component hierarchy (components.*, pages.*)
   - Use descriptive, nested keys (header.nav.home)
   - Match component structure in JSON

3. Update locales:
   - Add all keys to src/locales/en.json
   - Maintain consistent naming across app

AI 提取后:

import { useIntl } from "react-intl";

function WelcomeCard() {
  const intl = useIntl();

  return (
    <div className="card">
      <h2>{intl.formatMessage({ id: "welcome.title" })}</h2>
      <p>{intl.formatMessage({ id: "welcome.description" })}</p>
      <button>{intl.formatMessage({ id: "welcome.getStarted" })}</button>
    </div>
  );
}

生成的 en.json:

{
  "welcome.title": "Welcome to our platform",
  "welcome.description": "Start your journey with us today",
  "welcome.getStarted": "Get started"
}

批量处理

对于多个组件,选择所有文件并使用同一个综合性提示。像 Cursor、GitHub Copilot 等 AI IDE 可以同时处理多个文件,确保应用内 key 命名一致。

翻译生成

当 AI IDE 提取完 key 后,生成翻译:

npx lingo.dev@latest run

这样会创建源文件的翻译版本:

src/locales/
  en.json    (source with extracted keys)
  es.json    (Spanish translations)
  fr.json    (French translations)
  de.json    (German translations)

校验

提取后,验证你的配置:

检查翻译覆盖率:

npx lingo.dev@latest run --frozen

该命令会在有缺失翻译时失败,确保翻译覆盖完整。

用不同语言环境测试:

// Switch locale in your app to verify translations work
<IntlProvider locale="es" messages={spanishMessages}>
  <WelcomeCard />
</IntlProvider>