Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@vendure/ngx-translate-extract

vendure-ecommerce109.6kMIT9.4.1TypeScript support: included

Extract strings from projects using ngx-translate

angular, ionic, ngx-translate, extract, extractor, translate, translation, i18n, gettext

readme

ngx-translate-extract

Angular translations extractor (plugin for @ngx-translate)

Angular 14+, Ivy and Angular Universal (SSR) compatible

Extract translatable (ngx-translate) strings and save as a JSON or Gettext pot file. Merges with existing strings if the output file already exists.

History

This project was originally created by Kim Biesbjerg. Unfortunately he was unable to continue to maintain it so the Vendure team agreed to take over maintenance of this fork.

Install

Install the package in your project:

npm install @vendure/ngx-translate-extract --save-dev
# or
yarn add @vendure/ngx-translate-extract --dev

Choose the version corresponding to your Angular version:

Angular ngx-translate-extract
>=17 9.x
13 – 16 8.x
8 – 12 @biesbjerg/ngx-translate-extract 7.x

Add a script to your project's package.json:

"scripts": {
  "i18n:init": "ngx-translate-extract --input ./src --output ./src/assets/i18n/template.json --key-as-default-value --replace --format json",
  "i18n:extract": "ngx-translate-extract --input ./src --output ./src/assets/i18n/{en,da,de,fi,nb,nl,sv}.json --clean --format json"
}

You can now run npm run i18n:extract and it will extract strings from your project.

Usage

Extract from dir and save to file

ngx-translate-extract --input ./src --output ./src/assets/i18n/strings.json

Extract from multiple dirs

ngx-translate-extract --input ./src-a ./src-b --output ./src/assets/i18n/strings.json

Extract and save to multiple files using path expansion

ngx-translate-extract --input ./src --output ./src/i18n/{da,en}.json

Strip prefix from the generated json keys

Useful when loading multiple translation files in the same application and prefixing them automatically

ngx-translate-extract --input ./src --output ./src/i18n/{da,en}.json --strip-prefix 'PREFIX.'

Cache for consecutive runs

If your project grows rather large, runs can take seconds. With this cache, unchanged files don't need to be parsed again, keeping consecutive runs under .5 seconds.

ngx-translate-extract --cache-file node_modules/.i18n-cache/my-cache-file --input ./src --output ./src/i18n/{da,en}.json

JSON indentation

Tabs are used by default for indentation when saving extracted strings in json formats:

If you want to use spaces instead, you can do the following:

ngx-translate-extract --input ./src --output ./src/i18n/en.json --format-indentation ' '

Sorting

Extracted keys are by default not sorted. You can enable sorting by using the --sort or -s flag.

If sorting is enabled, the keys will be sorted using the default variant sort sensitivity. Other sort sensitivity options are also available using the --sort-sensitivity or -ss flag:

  • base: Strings that differ in base letters are unequal. For example a !== b, a === á, a === A
  • accent: Strings that differ in base letters and accents are unequal. For example a !== b, a !== á, a === A
  • case: Strings that differ in base letters or casing are unequal. For example a !== b, a === á, a !== A
  • variant: Strings that differ in base letters, accents, or casing are unequal. For example a !== b, a !== á, a !== A

Marker function

If you want to extract strings that are not passed directly to NgxTranslate.TranslateService's get()/instant()/stream() methods, or its translate pipe or directive, you can wrap them in the marker function from @ngx-translate/core to let ngx-translate-extract know you want to extract them.

Example: Using the marker function

// your-component.ts
import { Component, inject } from '@angular/core';
import { TranslateService, _ } from '@ngx-translate/core';

const welcomeMessage = _('app.your-component.welcome');

@Component({
  selector: 'your-component',
  template: `<p>{{ message }}</p>`,
})
export class YourComponent {
  private readonly translate = inject(TranslateService);

  readonly message = this.translate.instant(welcomeMessage);
}

For more advanced use cases where a marker pipe or directive is required, or if you are using a version of ngx-translate prior to v16, you can use the following library:

npm install @colsen1991/ngx-translate-extract-marker

See @colsen1991/ngx-translate-extract-marker documentation for more information.

Commandline arguments

Usage:
ngx-translate-extract [options]

Output
  --format, -f                Format        [string] [choices: "json", "namespaced-json", "pot"] [default: "json"]
  --format-indentation, --fi  Format indentation (JSON/Namedspaced JSON)                  [string] [default: "\t"]
  --sort, -s                  Sort strings in alphabetical order                                         [boolean]
  --sort-sensitivity, -ss     Sensitivity when sorting strings (only when sort is enabled)               [string]
  --clean, -c                 Remove obsolete strings after merge                                        [boolean]
  --replace, -r               Replace the contents of output file if it exists (Merges by default)       [boolean]
  --strip-prefix, -sp         Strip prefix from key                                                       [string]
  --po-source-locations       Include file location comments in .po files                [boolean] [default: true]

Extracted key value (defaults to empty string)
  --key-as-default-value, -k           Use key as default value                                          [boolean]
  --key-as-initial-default-value, -ki  Use key as initial default value                                  [boolean]
  --null-as-default-value, -n          Use null as default value                                         [boolean]
  --string-as-default-value, -d        Use string as default value                                        [string]

Options:
  --version, -v  Show version number                                                                     [boolean]
  --help, -h     Show help                                                                               [boolean]
  --input, -i    Paths you would like to extract strings from. You can use path expansion, glob patterns and
                 multiple paths                                               [array] [required] [default: ["./"]]
  --output, -o   Paths where you would like to save extracted strings. You can use path expansion, glob
                 patterns and multiple paths                                                    [array] [required]
  --cache-file   Cache parse results to speed up consecutive runs                                         [string]
  --marker, -m   Custom marker function name                                                              [string]

Examples:
  ngx-translate-extract -i ./src-a/ -i ./src-b/ -o strings.json             Extract (ts, html) from multiple paths
  ngx-translate-extract -i './{src-a,src-b}/' -o strings.json               Extract (ts, html) from multiple paths using brace expansion
  ngx-translate-extract -i ./src/ -o ./i18n/da.json -o ./i18n/en.json       Extract (ts, html) and save to da.json and en.json
  ngx-translate-extract -i ./src/ -o './i18n/{en,da}.json'                  Extract (ts, html) and save to da.json and en.json using brace expansion
  ngx-translate-extract -i './src/**/*.{ts,tsx,html}' -o strings.json       Extract from ts, tsx and html
  ngx-translate-extract -i './src/**/!(*.spec).{ts,html}' -o strings.json   Extract from ts, html, excluding files with ".spec"
  ngx-translate-extract -i './src/' -o strings.json -sp 'PREFIX.'           Strip the prefix "PREFIX." from the json keys

Note for GetText users

Please pay attention of which version of gettext-parser you actually use in your project. For instance, gettext-parser:1.2.2 does not support HTML tags in translation keys.

Credits

  • Original library, idea and code: Kim Biesbjerg ❤️
  • Further updates and improvements by bartholomej ❤️
  • Further updates and improvements by P4 ❤️
  • Further updates and improvements by colsen1991 ❤️
  • Further updates and improvements by tmijieux ❤️

changelog

Changelog

v9.4.1 (2025-06-27)

  • Fix parser not detecting TranslateService when used via inline-injection (#74)
  • Fix issue where brace patterns were ignored due to escaped braces on Windows (#72)

v9.4.0 (2024-12-17)

  • Use relative paths in .po file source comments
  • Add po-source-locations CLI option to control whether source locations are included in .po files (#63)

v9.3.1 (2024-11-19)

  • Resolve runtime error with CommonJS module imports from 'typescript' (#60)
  • Fix extraction of translation keys from nested function expressions (#61)

v9.3.0 (2024-11-18)

  • Fix parser not locating TranslateService in private fields using the # syntax (#55)
  • Add support for the ngx-translate _() marker function (#57)

v9.2.1 (2024-07-19)

  • Fix service parser to recognize the TranslateService property from an aliased superclass (#53)

v9.2.0 (2024-06-10)

Contains all changes from v9.2.0-next.0 plus:

  • Make sort sensitivity opt-in and configurable (#41)
  • Fix service and function parsing when used after bracket syntax casting expression (#51)

v9.2.0-next.0 (2024-05-21)

This is a pre-release available as @vendure/ngx-translate-extract@next. Due to some significant refactors to internals, we are releasing a pre-release version to allow for testing before the final release.

It contains the following changes:

  • Support finding translations pipe in KeyedRead nodes (#47)
  • Fix marker function parsing when used after bracket syntax casting expression (#45)
  • Add key-as-initial-default-value flag (#49)
  • Add support for extraction of translation keys from function expressions (#46)

v9.1.1 (2024-03-08)

  • Fix TranslateService not resolved when injected with readonly keyword (#39)

v9.1.0 (2024-02-05)

  • Add support for caching via the new --cache-file option (#38)

v9.0.3 (2023-11-28)

  • Fix RangeError: Maximum call stack size exceeded on nested templates (#34)
  • Fix alphabetical order of extracted keys (#35)

v9.0.2 (2023-11-24)

  • Fix import from glob packages (#31)
  • Fix extract for Windows file paths (#32)

v9.0.1 (2023-11-23)

  • Update dependencies & removed unused dependencies (#29)
  • fix: Fix syntax error when parsing tsconfig file (#30) Fixes #24

v9.0.0 (2023-11-21)

  • feat: Add support for new Angular v17 control flow syntax (#27)

BREAKING CHANGES

  • minimum angular version required bumped to 17
  • minimum node version required bumped to v18.13.0 to be aligned with the Angular 17 requirements
  • minimum TypeScript version required bumped to v5.2 to be aligned with the Angular 17 requirements

v8.3.0 (2023-11-21)

  • Add support for the --strip-prefix option (#23)

v8.2.3 (2023-09-27)

  • Enable extraction from subclasses without declaration (#21)
  • Fix chained function calls (#21)
  • Add tests (#21)
  • Extract translations when service injected using inject() function (#22)

v8.2.2 (2023-08-10)

  • Fix extraction error with --null-as-default-value (#18)

v8.2.1 (2023-07-21)

  • Fix extraction error introduced in the last version (#14)
  • Add braces to dependencies (#9)

v8.2.0 (2023-07-03)

  • Add source locations in PO compiler output (#13)

v8.1.1 (2023-05-11)

  • Update tsquery dependency to allow usage with TypeScript v5 (#10)

v8.1.0 (2023-03-15)

  • Accommodate marker pipe and directive
  • Enable support for other marker packages apart from the original from Kim Biesbjerg
  • Merged P4's PRs (#1, #2) in order to improve the pipe parser when it comes to pipe args and structural directives
  • Fixed some botched imports
  • Re-added --marker/-m option to CLI thanks to tmijieux's PR
  • Moved to eslint and fixed errors/warnings
  • Other minor clerical changes and small refactoring
  • Remove dependency on a specific version of the Angular compiler. Instead, we rely on the peer dependency. #3

v8.0.5 (2023-03-02)

  • fix(pipe-parser): Search for pipe in structural directives #1

    This fix will now detect the pipe in code like this:

    <ng-container *ngTemplateOutlet="section; context: {
      title: 'example.translation.key' | translate
    }"></ng-container>
  • fix: Find uses of translate pipe in pipe arguments #2

    Fixes the following:

  {{ 'value' | testPipe: ('test1' | translate) }} // finds nothing, misses 'test1'
  {{ 'Hello' | translate: {world: ('World' | translate)} }} // finds 'Hello', misses 'World'
  {{ 'previewHeader' | translate:{filename: filename || ('video' | translate)} }} // finds 'previewHeader', misses 'video'

v8.0.3 (2022-12-15)

  • First package published under the @vendure namespace
  • Update references in README

v8 - v8.0.2

Prior to v8

See the releases in the original repo.