作者:
    Creation:2025-04-18Last update:2026-10-08

    使用 Intlayer 翻译你的 Angular 19 (Webpack) 网站

    目录

    为什么选择 Intlayer 而不是其他方案?

    与“ngx-translate”或“angular-l10n”等主要解决方案相比,Intlayer 是一个具有集成优化的解决方案,例如:

    Intlayer 经过优化,可与 Angular 完美配合,提供组件级内容范围、延迟加载翻译以及​​扩展国际化 (i18n) 所需的所有功能。

    您无需在页面中加载庞大的 JSON 文件,而是只加载所需的内容。Intlayer 可以帮助 将您的打包产物和页面体积减少多达 50%。

    将应用程序内容与组件就近维护在相应作用域内,极大提升了大体量应用的可维护性。您可以直接复制或删除单个功能目录,而无需承担检查整个全局内容代码库的认知负担。此外,Intlayer 提供 完整的 TypeScript 类型支持,确保内容的准确性与安全性。

    内容就近组织 (Co-location) 显著减少了大型语言模型 (LLM) 所需的上下文。Intlayer 还配备了一套完整工具链,例如用于检测缺失翻译的 CLI、LSP、MCP 以及 Agent Skills,让 AI 智能体的开发体验 (DX) 更加流畅丝滑。

    在 CI/CD 流水线中,使用您自选的 LLM(直接基于您自有的 AI 提供商 API 计费)实现自动化翻译。Intlayer 还提供了可自动提取内容的 编译器,并配备了 Web 平台 / CMS 以便在后台管理系统中执行翻译。

    将大型 JSON 文件全局挂载到各个组件容易导致渲染性能下降与响应迟滞。Intlayer 会在构建阶段自动优化内容加载。

    Intlayer 不仅仅是一个简单的 i18n 解决方案。它还提供了 支持自托管的可视化编辑器 以及 完整的 CMS。借此,您可以 实时 管理多语言内容,让译者、文案及团队其他成员实现无缝协作。内容可存储在本地和/或远程服务器上。

    在 Angular 应用中设置 Intlayer 的分步指南

    ide.intlayer.org
    intlayer-angular-19-template.vercel.app

    查看 GitHub 上的应用模板。

    1. 安装依赖

      使用 npm 安装必要的包:

      bash
      npx intlayer init --interactive
      
      --interactive 标志是可选的。如果你是 AI 代理,请使用 intlayer-cli init。
      此命令将检测你的环境并安装所需的包。例如:
      bash
      npm install intlayer angular-intlayer
      npm install @angular-builders/custom-webpack --save-dev
      
      • intlayer

        核心包,为配置管理、翻译、内容声明、转译和 CLI 命令提供国际化工具。

      • angular-intlayer 将 Intlayer 与 Angular 应用集成的包。它为 Angular 国际化提供上下文 Provider 和 Hook。

      • @angular-builders/custom-webpack 自定义 Angular CLI 的 Webpack 配置所需。

    2. 配置你的项目

      架构

      在此架构中,angular-intlayer 提供 provideIntlayer(),并在 src/app/app.config.ts 中注册,以便每个组件都能通过 useIntlayer signal 读取其内容。Angular CLI 切换为自定义 Webpack 构建器,webpack.config.ts 将 Intlayer 插件合并到构建中,以监视并重新构建你的内容声明。内容声明文件与组件一起放置在 src/app/ 中。

      bash
      .
      ├── src
      │   ├── app
      │   │   ├── app.component.html        # Root template reading the content signal
      │   │   ├── app.component.ts          # Root component using useIntlayer
      │   │   ├── app.config.ts             # Application config with provideIntlayer()
      │   │   ├── app.content.ts            # App content declaration
      │   │   └── locale-switcher.component.ts
      │   └── main.ts
      ├── angular.json                      # Custom Webpack builder for build and serve
      ├── intlayer.config.ts
      ├── package.json
      ├── tsconfig.json
      └── webpack.config.ts                 # mergeConfig() from angular-intlayer/webpack
      

      配置

      创建一个配置文件来配置应用的语言:

      intlayer.config.ts
      import { Locales, type IntlayerConfig } from "intlayer";
      
      const config: IntlayerConfig = {
        internationalization: {
          locales: [
            Locales.ENGLISH,
            Locales.FRENCH,
            Locales.SPANISH,
            // 你的其他语言
          ],
          defaultLocale: Locales.ENGLISH,
        },
      };
      
      export default config;
      
      通过此配置文件,你可以设置本地化 URL、中间件重定向、cookie 名称、内容声明的位置和扩展名、禁用 Intlayer 在控制台中的日志等等。有关可用参数的完整列表,请参阅配置文档。
    3. 在你的 Angular 配置中集成 Intlayer

      要将 Intlayer 与 Angular CLI 集成,你需要使用自定义构建器。本指南假设你使用 Webpack(许多 Angular 项目的默认设置)。

      首先,修改你的 angular.json 以使用自定义 Webpack 构建器。更新 build 和 serve 配置:

      angular.json
      {
        "projects": {
          "your-app-name": {
            "architect": {
              "build": {
                "builder": "@angular-builders/custom-webpack:browser", // 替换 "@angular-devkit/build-angular:application"
                "options": {
                  "customWebpackConfig": {
                    "path": "./webpack.config.ts",
                    "mergeStrategies": { "module.rules": "prepend" },
                  },
                  "main": "src/main.ts", // 替换 "browser": "src/main.ts"
                  // ...
                },
              },
              "serve": {
                "builder": "@angular-builders/custom-webpack:dev-server", // 替换 "@angular-devkit/build-angular:dev-server"
              },
            },
          },
        },
      }
      
      确保在 angular.json 中用你项目的实际名称替换 your-app-name。

      接下来,在项目的根目录创建一个 webpack.config.ts 文件:

      webpack.config.ts
      import { mergeConfig } from "angular-intlayer/webpack";
      
      export default mergeConfig({});
      
      mergeConfig 函数使用 Intlayer 配置 Webpack。它注入 IntlayerPlugin(处理内容声明文件)并设置别名以获得最佳性能。
    4. 声明你的内容

      创建并管理你的内容声明以存储翻译:

      src/app/app.content.ts
      import { t, type Dictionary } from "intlayer";
      
      const appContent = {
        key: "app",
        content: {
          title: t({
            zh: "你好",
            en: "Hello",
            fr: "Bonjour",
            es: "Hola",
          }),
          congratulations: t({
            zh: "恭喜!你的应用正在运行。🎉",
            en: "Congratulations! Your app is running. 🎉",
            fr: "Félicitations! Votre application est en cours d'exécution. 🎉",
            es: "¡Felicidades! Tu aplicación está en ejecución. 🎉",
          }),
          exploreDocs: t({
            zh: "浏览文档",
            en: "Explore the Docs",
            fr: "Explorer les Docs",
            es: "Explorar los Docs",
          }),
          learnWithTutorials: t({
            zh: "通过教程学习",
            en: "Learn with Tutorials",
            fr: "Apprendre avec les Tutoriels",
            es: "Aprender con los Tutorios",
          }),
          cliDocs: "CLI Docs",
          angularLanguageService: t({
            zh: "Angular 语言服务",
            en: "Angular Language Service",
            fr: "Service de Langage Angular",
            es: "Servicio de Lenguaje Angular",
          }),
          angularDevTools: "Angular DevTools",
          github: "Github",
          twitter: "Twitter",
          youtube: "Youtube",
        },
      } satisfies Dictionary;
      
      export default appContent;
      
      你的内容声明可以定义在应用的任何地方,只要它们包含在 contentDir 目录中(默认为 ./src)。并且匹配内容声明文件扩展名(默认为 .content.{json,ts,tsx,js,jsx,mjs,cjs,md,mdx,yaml,yml})。
      有关更多详情,请参阅内容声明文档。
    5. 在你的代码中使用 Intlayer

      要在整个 Angular 应用中使用 Intlayer 的国际化功能,你需要在应用配置中提供 Intlayer。

      src/app/app.config.ts
      import { ApplicationConfig } from "@angular/core";
      import { provideRouter } from "@angular/router";
      import { provideIntlayer } from "angular-intlayer";
      import { routes } from "./app.routes";
      
      export const appConfig: ApplicationConfig = {
        providers: [
          provideRouter(routes),
          provideIntlayer(), // 在此处添加 Intlayer 提供者
        ],
      };
      

      然后,你可以在任何组件中使用 useIntlayer 函数。

      src/app/app.component.ts
      import { Component } from "@angular/core";
      import { RouterOutlet } from "@angular/router";
      import { useIntlayer } from "angular-intlayer";
      
      @Component({
        selector: "app-root",
        standalone: true,
        imports: [RouterOutlet],
        templateUrl: "./app.component.html",
        styleUrl: "./app.component.css",
      })
      export class AppComponent {
        content = useIntlayer("app");
      }
      

      在你的模板中:

      src/app/app.component.html
      <div class="content">
        <h1>{{ content().title }}</h1>
        <p>{{ content().congratulations }}</p>
      </div>
      

      Intlayer 内容作为 Signal 返回,所以你通过调用 signal 来访问值:content().title。

    6. 更改内容的语言

      可选

      要更改内容的语言,你可以使用 useLocale 函数提供的 setLocale 函数。这允许你设置应用的语言环境并相应地更新内容。

      创建一个组件来在语言之间切换:

      src/app/locale-switcher.component.ts
      import { Component } from "@angular/core";
      import { CommonModule } from "@angular/common";
      import { useLocale } from "angular-intlayer";
      
      @Component({
        selector: "app-locale-switcher",
        standalone: true,
        imports: [CommonModule],
        template: `
          <div class="locale-switcher">
            <select
              [value]="locale()"
              (change)="setLocale($any($event.target).value)"
            >
              @for (loc of availableLocales; track loc) {
                <option [value]="loc">{{ loc }}</option>
              }
            </select>
          </div>
        `,
      })
      export class LocaleSwitcherComponent {
        localeCtx = useLocale();
      
        locale = this.localeCtx.locale;
        availableLocales = this.localeCtx.availableLocales;
        setLocale = this.localeCtx.setLocale;
      }
      

      然后,在你的 app.component.ts 中使用此组件:

      src/app/app.component.ts
      import { Component } from "@angular/core";
      import { RouterOutlet } from "@angular/router";
      import { useIntlayer } from "angular-intlayer";
      import { LocaleSwitcherComponent } from "./locale-switcher.component";
      
      @Component({
        selector: "app-root",
        standalone: true,
        imports: [RouterOutlet, LocaleSwitcherComponent],
        templateUrl: "./app.component.html",
        styleUrl: "./app.component.css",
      })
      export class AppComponent {
        content = useIntlayer("app");
      }
      

    配置 TypeScript

    Intlayer 使用模块扩充来发挥 TypeScript 的优势并使你的代码库更强大。

    自动补全

    翻译错误

    确保你的 TypeScript 配置包含自动生成的类型。

    tsconfig.json
    {
      // ... 你现有的 TypeScript 配置
      "include": [
        // ... 你现有的 TypeScript 配置
        ".intlayer/**/*.ts", // 包含自动生成的类型
      ],
    }
    

    Git 配置

    建议忽略 Intlayer 生成的文件。这可以避免将它们提交到你的 Git 仓库。

    为此,你可以在 .gitignore 文件中添加以下指令:

    bash
    #  忽略 Intlayer 生成的文件
    .intlayer
    

    VS Code 扩展

    为了提升你在 Intlayer 中的开发体验,你可以安装官方的 Intlayer VS Code 扩展。

    该扩展提供:

    • 翻译键的自动补全。
    • 缺失翻译的实时错误检测。
    • 翻译内容的内联预览。
    • 用于轻松创建和更新翻译的快速操作。

    有关如何使用该扩展的更多详情,请参阅 Intlayer VS Code 扩展文档。

    深入了解

    要进一步深入,你可以实现 可视化编辑器 或使用 CMS 外置你的内容。

    常见问题

    • @angular/localize(内置 i18n):消息被提取到 XLIFF 文件中,每个语言环境被编译进独立的构建产物中,这意味着每种语言对应一个部署产物,无法在运行时切换语言环境。
    • ngx-translate 和 Transloco:通过服务加载的运行时 JSON 目录,支持语言环境切换,但没有构建时类型安全。
    • Intlayer:最先进的解决方案。内容可以在代码库中的任何位置声明(靠近每个组件或集中管理),并在构建时进行编译,全链路类型安全,支持运行时语言环境切换、AI 翻译、可视化编辑器和 CMS。

    本指南涵盖 Angular 19。对于 Angular 21 及更高版本,请参阅 Angular 指南。另请参阅 为什么选择 Intlayer。

    远少于基于命名空间的方案,因为页面永远不会下载它不渲染的语言目录。构建时编译器将 useIntlayer 调用替换为组件使用的确切字典条目,因此未使用的键和未使用的语言都会被自动丢弃,并且 动态字典 会按语言环境拆分剩余内容。与常规替代方案相比,Intlayer 可将 bundle 和页面体积减少高达 50%。请参阅 Bundle 体积优化 和 性能基准。

    基本可以。请按照 ngx-translate 迁移指南 或 Transloco 迁移指南 迁移内容。您也可以逐步迁移:JSON 同步插件 将现有的 JSON 目录作为单一真实来源(source of truth),并生成 Intlayer 字典,使两个层在逐个组件迁移时保持同步。

    可以。JSON 同步插件 将您的 /messages/{locale}/{namespace}.json 文件作为单一真实来源(source of truth),并双向生成 Intlayer 字典。PO 同步插件 对 gettext 目录执行相同的操作,而 按语言环境组织的文件 允许您按语言拆分内容,而不是将所有语言打包到一个文件中。

    不需要。运行 npx intlayer extract,Intlayer 会读取您的源码文件,提取面向用户的字符串,并在每个组件旁边生成 .content 文件,这样您只需审查 diff,而无需手动逐一复制字符串到语言目录中。请参阅 extract 命令。

    如需全自动流程,Intlayer Compiler 可以在构建时对 JSX、TSX、Vue 和 Svelte 源码执行相同操作,在每次更改时自动生成字典,完全无需手动维护键名。它通过静态分析工作,因此仅在运行时存在的字符串无法被捕获,并且需要少量注解以区分用户文本和应用程序逻辑。

    共有 5 个工具,均为可选:

    • VS Code 扩展:从 useIntlayer 键跳转到声明它的内容文件,从组件中提取内容,并从命令面板或专属的 Intlayer 选项卡运行 build、fill、test、push 和 pull。
    • LSP 服务器:在任何支持 LSP 的编辑器中提供相同的感知能力,支持跳转到定义、查找所有引用、悬停预览翻译值、键和字段的自动补全,以及在键未声明时发出警告。它还可以解析 i18next、react-i18next、next-intl 和 use-intl 调用,助力平滑迁移。
    • MCP 服务器:向 Cursor、VS Code、Claude Desktop、Claude Code 和 ChatGPT 公开 Intlayer 文档与 CLI,使 AI 助手能够基于最新文档进行准确回答,并能自行运行 intlayer fill 等命令。
    • Agent Skills:针对特定领域的技能(如 intlayer-config、intlayer-cli 和 intlayer-content,以及每个框架对应的专属技能),教导 AI 代理您的路由配置和内容节点类型。
    • ESLint 插件:no-raw-text 规则标记硬编码字符串,并提供针对静态字典键和未使用内容的额外规则。