You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17库集成@angular/localize提取i18n翻译报错求助

Angular 17 共享库本地化配置修复方案

问题背景

在Angular 17环境下开发跨应用共享的布局库,希望复用主应用基于@angular/localize的本地化方案,但遇到以下问题:

  • 执行ng extract-i18n提取翻译时触发错误:An unhandled exception occurred: The "paths[1]" argument must be of type string. Received undefined,且指定日志文件无内容。
  • 尝试localize-extract工具生成的翻译文件为空,常规提取流程无法识别库中的i18n标记。

关键配置修正步骤

1. 库项目依赖与脚本配置

确保库的package.json中将@angular/localize列为生产依赖,并添加专用的提取脚本:

{
  "dependencies": {
    "@angular/localize": "^17.0.0"
  },
  "scripts": {
    "extract-i18n": "ng extract-i18n my-lib --output-path src/locale --format=xlf2"
  }
}

2. angular.json 库项目构建与提取配置

在angular.json的库项目节点下,完善extract-i18n和build配置:

"projects": {
  "my-lib": {
    "architect": {
      "build": {
        "builder": "@angular-devkit/build-angular:ng-packagr",
        "options": {
          "project": "projects/my-lib/ng-package.json",
          "localize": true
        }
      },
      "extract-i18n": {
        "builder": "@angular-devkit/build-angular:extract-i18n",
        "options": {
          "browserTarget": "my-lib:build",
          "outputPath": "src/locale",
          "format": "xlf2",
          "include": ["src/**/*.ts", "src/**/*.html"]
        }
      }
    }
  }
}
  • build配置中启用localize: true,确保库构建时保留本地化标记。
  • extract-i18n明确指定要扫描的源文件范围,避免遗漏。

3. 库组件i18n标记规范

确保组件模板和代码中的i18n标记符合Angular 17规范,例如:

  • 模板中:<p i18n="@@libWelcomeText">欢迎使用共享布局库</p>
  • TypeScript代码中:
    import { $localize } from '@angular/localize';
    const alertMessage = $localize`@@libAlert:操作成功`;
    

4. 主应用集成库本地化的提取配置

主应用执行提取时,需要包含库的源文件路径,修改主应用angular.json的extract-i18n配置:

"extract-i18n": {
  "builder": "@angular-devkit/build-angular:extract-i18n",
  "options": {
    "browserTarget": "my-app:build",
    "outputPath": "src/locale",
    "include": ["src/**/*", "projects/my-lib/src/**/*"]
  }
}

验证方法

  1. 在库项目目录下执行npm run extract-i18n,检查src/locale目录下是否生成包含库翻译条目的.xlf文件。
  2. 在主应用目录下执行ng extract-i18n,确认输出的翻译文件中包含库的i18n标记内容。

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:07:30