Skip to content
프로젝트

daniel-sc/ng-extract-i18n-merge

GitHub에서 보기

소개

Extract and merge i18n xliff translation files for angular projects.

웹 및 앱 개발

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

npm Coverage Status CodeQL

Angular extract i18n and merge

This extends Angular CLI to improve the i18n extraction and merge workflow. New/removed translations are added/removed from the target translation files and translation states are managed. Additionally, translation files are normalized (whitespace, stable sort) so that diffs are easy to read (and translations in PRs might actually get reviewed ;-) ).

Video walkthrough: Why and how to set up ng-extract-i18n-merge with Angular i18n. The video explains where this library fits into Angular's i18n workflow.

[!TIP] Translate new Angular messages after extraction. doloc is a localization API from this package's maintainer, @daniel-sc. Run ng extract-i18n, send the target XLIFF file to doloc, and get the translated file back in the same script or CI run. Your repository stays the source of truth.

Follow the Angular integration guide, or start free with your own XLIFF file. The free plan includes 200 source texts per month.

Install

Prerequisites: i18n setup with defined target locales in angular.json - as documented here.

ng add ng-extract-i18n-merge

Nx

Tested with Angular 20.3.9 / Nx 22.5.0, Angular 21.0.0 / Nx 22.5.0, and Angular 22.0.0 / Nx 23.3.0, using the @angular/build:application builder. Your workspace needs @nx/angular (matching your Nx version) and Angular i18n configured, including target locales in the application's project.json.

From the workspace root, replace my-app with your project name:

npm install --save-dev ng-extract-i18n-merge
npx nx generate ng-extract-i18n-merge:ng-add --project=my-app
npx nx run my-app:extract-i18n --skip-nx-cache

Setup configures the selected project's extract-i18n target using Nx's Angular compatibility support. Skip Nx caching because merging reads and updates existing translation files in place. Historical workspace.json setups are not covered by this integration test.

Upgrade from 1.x.x to 2.0.0

First run ng update ng-extract-i18n-merge@2, then follow the v3 upgrade below. See the archived v1 migration guide for breaking changes.

Upgrade from 2.x.x to 3.0.0

Run ng update ng-extract-i18n-merge to update to v3.0.0 using the Angular update mechanism. This release drops support for Angular 19 and older. The defaults for prettyNestedTags and sort changed to false and "stableAlphabetNew" respectively. builderI18n now defaults to @angular/build:extract-i18n instead of @angular-devkit/build-angular:extract-i18n. During ng update existing builder configurations are updated to keep the previous behaviour (except for builderI18n, where the new default is best for most setups).

Usage

ng extract-i18n # yes, same as before - this replaces the original builder

Angular owns the message IDs: for example, $localize messages containing "Hello" and " Hello " (with surrounding spaces) can have different generated IDs. This library normalizes whitespace after extraction without changing IDs. Fuzzy matching reuses translations from obsolete entries; it does not combine entries whose IDs both remain in the source. Keep source whitespace consistent, or use custom IDs such as @@greeting, reusing an ID only for the same message text.

With the default Angular extractor, conflicting text under the same ID produces a warning. To fail instead, set "builderI18nOptions": {"i18nDuplicateTranslation": "error"} on the extract-i18n target (Angular also supports warning and ignore). This check detects conflicting text under the same ID, not similar text under different IDs.

Configuration

In your angular.json the target extract-i18n that can be configured with the following options:

Name Default Description
buildTarget Inferred from current setup by ng add A build builder target to extract i18n messages in the format of project:target[:configuration]. See https://angular.io/cli/extract-i18n#options
format Inferred from current setup by ng add Any of xlf, xlif, xliff, xlf2, xliff2
outputPath Inferred from current setup by ng add Path to folder containing all (source and target) translation files.
targetFiles Inferred from current setup by ng add Filenames (relative to outputPath of all target translation files (e.g. ["messages.fr.xlf", "messages.de.xlf"]).
sourceLanguageTargetFile null If this is set (to one of the targetFiles), new translations in that target file will be set to state="final" (instead of default state="new"). This file can be used to manage changes to the source texts: when a translator updates the target, this tool will hint the developer to update the code occurrences.
sourceFile messages.xlf. ng add tries to infer non default setups. Filename (relative to outputPath of source translation file (e.g. "translations-source.xlf").
removeIdsWithPrefix [] List of prefix strings. All translation units with matching id attribute are removed. Useful for excluding duplicate library translations. Cannot be used in combination with includeIdsWithPrefix.
includeIdsWithPrefix [] List of prefix strings. When non-empty, only translations units with matching id are included. Useful for extracting translations of a single library in a multi-library project. Cannot be used in combination with removeIdsWithPrefix.
fuzzyMatch true Whether translation units without matching IDs are fuzzy matched by source text.
resetTranslationState true Reset the translation state to new/initial for new/changed units.
prettyNestedTags false If source/target only contains xml nodes (interpolations, nested html), true formats these with line breaks and indentation. false keeps the original angular single line format. Note: while true was the historic implementation, it is not recommended, as it adds whitespace between tags that had no whitespace in between and increases bundle sizes.
selfClosingEmptyTargets true If false empty target nodes are non self-closing.
sortNestedTagAttributes false Attributes of xml nodes (interpolations, nested html) in source/target/meaning/description can be sorted for normalization.
collapseWhitespace true Collapsing of multiple whitespaces/line breaks in translation sources and targets. This handles changed leading/trailing whitespaces intelligently - i.e. updates the target accordingly without resetting the translation state when only leading/trailing whitespace was changed.
trim false Trim translation sources and targets.
includeContext false Whether to include the context information (like notes) in the translation files. This is useful for sending the target translation files to translation agencies/services. When sourceFileOnly, the context is retained only in the sourceFile.
includeContextLineNumber true If includeContext has been included allow the inclusion of line number to be optional. This can help reduce noise in the committed xlf files for strings that have not changed but their line number was shifted due to other changes in the file.
includeMeaningAndDescription true Whether to include the meaning and description information in the translation files.
newTranslationTargetsBlank false When false (default) the "target" of new translation units is set to the "source" value. When true, an empty string is used. When 'omit', no target element is created.
sort "stableAlphabetNew" Sorting of all translation units in source and target translation files. Supported:
"idAsc" (sort by translation IDs),
"stableAppendNew" (keep existing sorting, append new translations at the end),
"stableAlphabetNew" (keep existing sorting, sort new translations next to alphabetical close IDs).
builderI18n "@angular/build:extract-i18n" The builder to use for i18n extraction. Any custom builder should handle the same options as the default angular builder (buildTarget, outputPath, outFile, format, progress).
builderI18nOptions {} Additional options passed to builderI18n and validated by that builder, e.g. {"i18nDuplicateTranslation": "error"} or {"extraWebpackConfig": "tools/webpack-version.partial.js"}. buildTarget, outputPath, outFile, format, and progress remain controlled by this library.
verbose false Extended/debug output - it is recommended to use this only for manual debugging.

Contribute

Feedback and PRs always welcome :-)

Before developing complex changes, I'd recommend opening an issue to discuss whether the indented goals match the scope of this package.

Run npm run test-nx -- 20, npm run test-nx -- 21, or npm run test-nx -- 22 for the Nx integration test (defaults to Angular 21). Each case builds and packs this package, installs it in a temporary workspace with pinned Nx/Angular versions, and checks setup, extraction, and merging. It requires npm registry access. CI runs all three cases on Node 22.22.3.

관련 프로젝트 살펴보기

불러오는 중…