项目作者: i18next

项目描述 :
Scan your code, extract translation keys/values, and merge them into i18n resource files.
高级语言: JavaScript
项目地址: git://github.com/i18next/i18next-scanner.git
创建时间: 2015-03-17T13:53:08Z
项目社区:https://github.com/i18next/i18next-scanner

开源协议:MIT License

下载


i18next-scanner build status Coverage Status

NPM

Scan your code, extract translation keys/values, and merge them into i18n resource files.

Turns your code

  1. i18n._('Loading...');
  2. i18n._('Backslashes in single quote: \' \\ \'');
  3. i18n._('This is \
  4. a multiline \
  5. string');
  6. i18n.t('car', { context: 'blue', count: 1 }); // output: 'One blue car'
  7. i18n.t('car', { context: 'blue', count: 2 }); // output: '2 blue cars'
  8. <Trans i18nKey="some.key">Default text</Trans>

into resource files

  1. {
  2. "Loading...": "Wird geladen...", // uses existing translation
  3. "Backslashes in single quote: ' \\ '": "__NOT_TRANSLATED__", // returns a custom string
  4. "This is a multiline string": "this is a multiline string", // returns the key as the default value
  5. "car": "car",
  6. "car_blue": "One blue car",
  7. "car_blue_plural": "{{count}} blue cars",
  8. "some": {
  9. "key": "Default text"
  10. }
  11. }

Notice

There is a major breaking change since v1.0, and the API interface and options are not compatible with v0.x.

Checkout Migration Guide while upgrading from earlier versions.

Features

  • Fully compatible with i18next - a full-featured i18n javascript library for translating your webapplication.
  • Support react-i18next for parsing the Trans component
  • Support Key Based Fallback to write your code without the need to maintain i18n keys. This feature is available since i18next@^2.1.0
  • A standalone parser API
  • A transform stream that works with both Gulp and Grunt task runner.
  • Support custom transform and flush functions.

Installation

  1. npm install --save-dev i18next-scanner

or

  1. npm install -g i18next-scanner

Usage

CLI Usage

  1. $ i18next-scanner
  2. Usage: i18next-scanner [options] <file ...>
  3. Options:
  4. -V, --version output the version number
  5. --config <config> Path to the config file (default: i18next-scanner.config.js)
  6. --output <path> Path to the output directory (default: .)
  7. -h, --help output usage information
  8. Examples:
  9. $ i18next-scanner --config i18next-scanner.config.js --output /path/to/output 'src/**/*.{js,jsx}'
  10. $ i18next-scanner --config i18next-scanner.config.js 'src/**/*.{js,jsx}'
  11. $ i18next-scanner '/path/to/src/app.js' '/path/to/assets/index.html'

Globbing patterns are supported for specifying file paths:

  • * matches any number of characters, but not /
  • ? matches a single character, but not /
  • ** matches any number of characters, including /, as long as it’s the only thing in a path part
  • {} allows for a comma-separated list of “or” expressions
  • ! at the beginning of a pattern will negate the match

Note: Globbing patterns should be wrapped in single quotes.

Examples

  1. const fs = require('fs');
  2. const chalk = require('chalk');
  3. module.exports = {
  4. input: [
  5. 'app/**/*.{js,jsx}',
  6. // Use ! to filter out files or directories
  7. '!app/**/*.spec.{js,jsx}',
  8. '!app/i18n/**',
  9. '!**/node_modules/**',
  10. ],
  11. output: './',
  12. options: {
  13. debug: true,
  14. func: {
  15. list: ['i18next.t', 'i18n.t'],
  16. extensions: ['.js', '.jsx']
  17. },
  18. trans: {
  19. component: 'Trans',
  20. i18nKey: 'i18nKey',
  21. defaultsKey: 'defaults',
  22. extensions: ['.js', '.jsx'],
  23. fallbackKey: function(ns, value) {
  24. return value;
  25. },
  26. // https://react.i18next.com/latest/trans-component#usage-with-simple-html-elements-like-less-than-br-greater-than-and-others-v10.4.0
  27. supportBasicHtmlNodes: true, // Enables keeping the name of simple nodes (e.g. <br/>) in translations instead of indexed keys.
  28. keepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], // Which nodes are allowed to be kept in translations during defaultValue generation of <Trans>.
  29. // https://github.com/acornjs/acorn/tree/master/acorn#interface
  30. acorn: {
  31. ecmaVersion: 2020,
  32. sourceType: 'module', // defaults to 'module'
  33. }
  34. },
  35. lngs: ['en','de'],
  36. ns: [
  37. 'locale',
  38. 'resource'
  39. ],
  40. defaultLng: 'en',
  41. defaultNs: 'resource',
  42. defaultValue: '__STRING_NOT_TRANSLATED__',
  43. resource: {
  44. loadPath: 'i18n/{{lng}}/{{ns}}.json',
  45. savePath: 'i18n/{{lng}}/{{ns}}.json',
  46. jsonIndent: 2,
  47. lineEnding: '\n'
  48. },
  49. nsSeparator: false, // namespace separator
  50. keySeparator: false, // key separator
  51. interpolation: {
  52. prefix: '{{',
  53. suffix: '}}'
  54. },
  55. metadata: {},
  56. allowDynamicKeys: false,
  57. },
  58. transform: function customTransform(file, enc, done) {
  59. "use strict";
  60. const parser = this.parser;
  61. const content = fs.readFileSync(file.path, enc);
  62. let count = 0;
  63. parser.parseFuncFromString(content, { list: ['i18next._', 'i18next.__'] }, (key, options) => {
  64. parser.set(key, Object.assign({}, options, {
  65. nsSeparator: false,
  66. keySeparator: false
  67. }));
  68. ++count;
  69. });
  70. if (count > 0) {
  71. console.log(`i18next-scanner: count=${chalk.cyan(count)}, file=${chalk.yellow(JSON.stringify(file.relative))}`);
  72. }
  73. done();
  74. }
  75. };

Standard API

  1. const fs = require('fs');
  2. const Parser = require('i18next-scanner').Parser;
  3. const customHandler = function(key) {
  4. parser.set(key, '__TRANSLATION__');
  5. };
  6. const parser = new Parser();
  7. let content = '';
  8. // Parse Translation Function
  9. // i18next.t('key');
  10. content = fs.readFileSync('/path/to/app.js', 'utf-8');
  11. parser
  12. .parseFuncFromString(content, customHandler) // pass a custom handler
  13. .parseFuncFromString(content, { list: ['i18next.t']}) // override `func.list`
  14. .parseFuncFromString(content, { list: ['i18next.t']}, customHandler)
  15. .parseFuncFromString(content); // use default options and handler
  16. // Parse Trans component
  17. content = fs.readFileSync('/path/to/app.jsx', 'utf-8');
  18. parser
  19. .parseTransFromString(content, customHandler) // pass a custom handler
  20. .parseTransFromString(content, { component: 'Trans', i18nKey: 'i18nKey', defaultsKey: 'defaults' })
  21. .parseTransFromString(content, { fallbackKey: true }) // Uses defaultValue as the fallback key when the i18nKey attribute is missing
  22. .parseTransFromString(content); // use default options and handler
  23. // Parse HTML Attribute
  24. // <div data-i18n="key"></div>
  25. content = fs.readFileSync('/path/to/index.html', 'utf-8');
  26. parser
  27. .parseAttrFromString(content, customHandler) // pass a custom handler
  28. .parseAttrFromString(content, { list: ['data-i18n'] }) // override `attr.list`
  29. .parseAttrFromString(content, { list: ['data-i18n'] }, customHandler)
  30. .parseAttrFromString(content); // using default options and handler
  31. console.log(parser.get());
  32. console.log(parser.get({ sort: true }));
  33. console.log(parser.get('translation:key', { lng: 'en'}));

Transform Stream API

The main entry function of i18next-scanner is a transform stream. You can use vinyl-fs to create a readable stream, pipe the stream through i18next-scanner to transform your code into an i18n resource object, and write to a destination folder.

Here is a simple example showing how that works:

  1. const scanner = require('i18next-scanner');
  2. const vfs = require('vinyl-fs');
  3. const sort = require('gulp-sort');
  4. const options = {
  5. // See options at https://github.com/i18next/i18next-scanner#options
  6. };
  7. vfs.src(['/path/to/src'])
  8. .pipe(sort()) // Sort files in stream by path
  9. .pipe(scanner(options))
  10. .pipe(vfs.dest('/path/to/dest'));

Alternatively, you can get a transform stream by calling createStream() as show below:

  1. vfs.src(['/path/to/src'])
  2. .pipe(sort()) // Sort files in stream by path
  3. .pipe(scanner.createStream(options))
  4. .pipe(vfs.dest('/path/to/dest'));

Gulp

Now you are ready to set up a minimal configuration, and get started with Gulp. For example:

  1. const gulp = require('gulp');
  2. const sort = require('gulp-sort');
  3. const scanner = require('i18next-scanner');
  4. gulp.task('i18next', function() {
  5. return gulp.src(['src/**/*.{js,html}'])
  6. .pipe(sort()) // Sort files in stream by path
  7. .pipe(scanner({
  8. lngs: ['en', 'de'], // supported languages
  9. resource: {
  10. // the source path is relative to current working directory
  11. loadPath: 'assets/i18n/{{lng}}/{{ns}}.json',
  12. // the destination path is relative to your `gulp.dest()` path
  13. savePath: 'i18n/{{lng}}/{{ns}}.json'
  14. }
  15. }))
  16. .pipe(gulp.dest('assets'));
  17. });

Grunt

Once you’ve finished the installation, add this line to your project’s Gruntfile:

  1. grunt.loadNpmTasks('i18next-scanner');

In your project’s Gruntfile, add a section named i18next to the data object passed into grunt.initConfig(), like so:

  1. grunt.initConfig({
  2. i18next: {
  3. dev: {
  4. src: 'src/**/*.{js,html}',
  5. dest: 'assets',
  6. options: {
  7. lngs: ['en', 'de'],
  8. resource: {
  9. loadPath: 'assets/i18n/{{lng}}/{{ns}}.json',
  10. savePath: 'i18n/{{lng}}/{{ns}}.json'
  11. }
  12. }
  13. }
  14. }
  15. });

API

There are two ways to use i18next-scanner:

Standard API

  1. const Parser = require('i18next-scanner').Parser;
  2. const parser = new Parser(options);
  3. const code = "i18next.t('key'); ...";
  4. parser.parseFuncFromString(code);
  5. const jsx = '<Trans i18nKey="some.key">Default text</Trans>';
  6. parser.parseTransFromString(jsx);
  7. const html = '<div data-i18n="key"></div>';
  8. parser.parseAttrFromString(html);
  9. parser.get();

parser.parseFuncFromString

Parse translation key from JS function

  1. parser.parseFuncFromString(content)
  2. parser.parseFuncFromString(content, { list: ['_t'] });
  3. parser.parseFuncFromString(content, function(key, options) {
  4. options.defaultValue = key; // use key as the value
  5. parser.set(key, options);
  6. });
  7. parser.parseFuncFromString(content, { list: ['_t'] }, function(key, options) {
  8. parser.set(key, options); // use defaultValue
  9. });

parser.parseTransFromString

Parse translation key from the Trans component

  1. parser.parseTransFromString(content);
  2. parser.parseTransFromString(context, { component: 'Trans', i18nKey: 'i18nKey' });
  3. // Uses defaultValue as the fallback key when the i18nKey attribute is missing
  4. parser.parseTransFromString(content, { fallbackKey: true });
  5. parser.parseTransFromString(content, {
  6. fallbackKey: function(ns, value) {
  7. // Returns a hash value as the fallback key
  8. return sha1(value);
  9. }
  10. });
  11. parser.parseTransFromString(content, function(key, options) {
  12. options.defaultValue = key; // use key as the value
  13. parser.set(key, options);
  14. });

parser.parseAttrFromString

Parse translation key from HTML attribute

  1. parser.parseAttrFromString(content)
  2. parser.parseAttrFromString(content, { list: ['data-i18n'] });
  3. parser.parseAttrFromString(content, function(key) {
  4. const defaultValue = key; // use key as the value
  5. parser.set(key, defaultValue);
  6. });
  7. parser.parseAttrFromString(content, { list: ['data-i18n'] }, function(key) {
  8. parser.set(key); // use defaultValue
  9. });

parser.get

Get the value of a translation key or the whole i18n resource store

  1. // Returns the whole i18n resource store
  2. parser.get();
  3. // Returns the resource store with the top-level keys sorted by alphabetical order
  4. parser.get({ sort: true });
  5. // Returns a value in fallback language (@see options.fallbackLng) with namespace and key
  6. parser.get('ns:key');
  7. // Returns a value with namespace, key, and lng
  8. parser.get('ns:key', { lng: 'en' });

parser.set

Set a translation key with an optional defaultValue to i18n resource store

  1. // Set a translation key
  2. parser.set(key);
  3. // Set a translation key with default value
  4. parser.set(key, defaultValue);
  5. // Set a translation key with default value using options
  6. parser.set(key, {
  7. defaultValue: defaultValue
  8. });

Transform Stream API

  1. const scanner = require('i18next-scanner');
  2. scanner.createStream(options, customTransform /* optional */, customFlush /* optional */);

customTransform

The optional customTransform function is provided as the 2nd argument for the transform stream API. It must have the following signature: function (file, encoding, done) {}. A minimal implementation should call the done() function to indicate that the transformation is done, even if that transformation means discarding the file.
For example:

  1. const scanner = require('i18next-scanner');
  2. const vfs = require('vinyl-fs');
  3. const customTransform = function _transform(file, enc, done) {
  4. const parser = this.parser;
  5. const content = fs.readFileSync(file.path, enc);
  6. // add your code
  7. done();
  8. };
  9. vfs.src(['/path/to/src'])
  10. .pipe(scanner(options, customTransform))
  11. .pipe(vfs.dest('path/to/dest'));

To parse a translation key, call parser.set(key, defaultValue) to assign the key with an optional defaultValue.
For example:

  1. const customTransform = function _transform(file, enc, done) {
  2. const parser = this.parser;
  3. const content = fs.readFileSync(file.path, enc);
  4. parser.parseFuncFromString(content, { list: ['i18n.t'] }, function(key) {
  5. const defaultValue = '__L10N__';
  6. parser.set(key, defaultValue);
  7. });
  8. done();
  9. };

Alternatively, you may call parser.set(defaultKey, value) to assign the value with a default key. The defaultKey should be unique string and can never be null, undefined, or empty.
For example:

  1. const hash = require('sha1');
  2. const customTransform = function _transform(file, enc, done) {
  3. const parser = this.parser;
  4. const content = fs.readFileSync(file.path, enc);
  5. parser.parseFuncFromString(content, { list: ['i18n._'] }, function(key) {
  6. const value = key;
  7. const defaultKey = hash(value);
  8. parser.set(defaultKey, value);
  9. });
  10. done();
  11. };

customFlush

The optional customFlush function is provided as the last argument for the transform stream API, it is called just prior to the stream ending. You can implement your customFlush function to override the default flush function. When everything’s done, call the done() function to indicate the stream is finished.
For example:

  1. const scanner = require('i18next-scanner');
  2. const vfs = require('vinyl-fs');
  3. const customFlush = function _flush(done) {
  4. const parser = this.parser;
  5. const resStore = parser.getResourceStore();
  6. // loop over the resStore
  7. Object.keys(resStore).forEach(function(lng) {
  8. const namespaces = resStore[lng];
  9. Object.keys(namespaces).forEach(function(ns) {
  10. const obj = namespaces[ns];
  11. // add your code
  12. });
  13. });
  14. done();
  15. };
  16. vfs.src(['/path/to/src'])
  17. .pipe(scanner(options, customTransform, customFlush))
  18. .pipe(vfs.dest('/path/to/dest'));

Default Options

Below are the configuration options with their default values:

  1. {
  2. compatibilityJSON: 'v3', // One of: 'v1', 'v2', 'v3', 'v4
  3. debug: false,
  4. removeUnusedKeys: false,
  5. sort: false,
  6. attr: {
  7. list: ['data-i18n'],
  8. extensions: ['.html', '.htm'],
  9. },
  10. func: {
  11. list: ['i18next.t', 'i18n.t'],
  12. extensions: ['.js', '.jsx'],
  13. },
  14. trans: {
  15. component: 'Trans',
  16. i18nKey: 'i18nKey',
  17. defaultsKey: 'defaults',
  18. extensions: ['.js', '.jsx'],
  19. fallbackKey: false,
  20. // https://react.i18next.com/latest/trans-component#usage-with-simple-html-elements-like-less-than-br-greater-than-and-others-v10.4.0
  21. supportBasicHtmlNodes: true, // Enables keeping the name of simple nodes (e.g. <br/>) in translations instead of indexed keys.
  22. keepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], // Which nodes are allowed to be kept in translations during defaultValue generation of <Trans>.
  23. // https://github.com/acornjs/acorn/tree/master/acorn#interface
  24. acorn: {
  25. ecmaVersion: 2020,
  26. sourceType: 'module', // defaults to 'module'
  27. },
  28. },
  29. lngs: ['en'],
  30. ns: ['translation'],
  31. defaultLng: 'en',
  32. defaultNs: 'translation',
  33. defaultValue: '',
  34. resource: {
  35. loadPath: 'i18n/{{lng}}/{{ns}}.json',
  36. savePath: 'i18n/{{lng}}/{{ns}}.json',
  37. jsonIndent: 2,
  38. lineEnding: '\n',
  39. },
  40. nsSeparator: ':',
  41. keySeparator: '.',
  42. pluralSeparator: '_',
  43. contextSeparator: '_',
  44. contextDefaultValues: [],
  45. interpolation: {
  46. prefix: '{{',
  47. suffix: '}}',
  48. },
  49. metadata: {},
  50. allowDynamicKeys: false,
  51. }

compatibilityJSON

Type: String Default: 'v3'

The compatibilityJSON version to use for plural suffixes.

See https://www.i18next.com/misc/json-format for details.

debug

Type: Boolean Default: false

Set to true to turn on debug output.

removeUnusedKeys

Type: Boolean or Function Default: false

Set to true to remove unused translation keys from i18n resource files. By default, this is set to false.

  1. { // Default
  2. removeUnusedKeys: false,
  3. }

If a function is provided, it will be used to decide whether an unused translation key should be removed.

  1. // Available since 4.6.0
  2. //
  3. // @param {string} lng The language of the unused translation key.
  4. // @param {string} ns The namespace of the unused translation key.
  5. // @param {array} key The translation key in its array form.
  6. // @return {boolean} Returns true if the unused translation key should be removed.
  7. removeUnusedKeys: function(lng, ns, key) {
  8. if (ns === 'resource') {
  9. return true;
  10. }
  11. return false;
  12. }

sort

Type: Boolean Default: false

Set to true if you want to sort translation keys in ascending order.

attr

Type: Object or false

If an Object is supplied, you can either specify a list of attributes and extensions, or override the default.

  1. { // Default
  2. attr: {
  3. list: ['data-i18n'],
  4. extensions: ['.html', '.htm']
  5. }
  6. }

You can set attr to false to disable parsing attribute as below:

  1. {
  2. attr: false
  3. }

func

Type: Object or false

If an Object is supplied, you can either specify a list of translation functions and extensions, or override the default.

  1. { // Default
  2. func: {
  3. list: ['i18next.t', 'i18n.t'],
  4. extensions: ['.js', '.jsx']
  5. }
  6. }

You can set func to false to disable parsing translation function as below:

  1. {
  2. func: false
  3. }

trans

Type: Object or false

If an Object is supplied, you can specify a list of extensions, or override the default.

  1. { // Default
  2. trans: {
  3. component: 'Trans',
  4. i18nKey: 'i18nKey',
  5. defaultsKey: 'defaults',
  6. extensions: ['.js', '.jsx'],
  7. fallbackKey: false,
  8. // https://react.i18next.com/latest/trans-component#usage-with-simple-html-elements-like-less-than-br-greater-than-and-others-v10.4.0
  9. supportBasicHtmlNodes: true, // Enables keeping the name of simple nodes (e.g. <br/>) in translations instead of indexed keys.
  10. keepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], // Which nodes are allowed to be kept in translations during defaultValue generation of <Trans>.
  11. // https://github.com/acornjs/acorn/tree/master/acorn#interface
  12. acorn: {
  13. ecmaVersion: 2020,
  14. sourceType: 'module', // defaults to 'module'
  15. },
  16. }
  17. }

You can set trans to false to disable parsing Trans component as below:

  1. {
  2. trans: false
  3. }

The fallbackKey can either be a boolean value, or a function like so:

  1. fallbackKey: function(ns, value) {
  2. // Returns a hash value as the fallback key
  3. return sha1(value);
  4. }

You can pass RexExp to trans.component in case you want to match multiple things:

  1. component: /Trans$/

lngs

Type: Array Default: ['en']

An array of supported languages.

ns

Type: String or Array Default: ['translation']

A namespace string or an array of namespaces.

defaultLng

Type: String Default: 'en'

The default language used for checking default values.

defaultNs

Type: String Default: 'translation'

The default namespace used if not passed to translation function.

defaultValue

Type: String or Function Default: ''

The default value used if not passed to parser.set.

Examples

Provides the default value with a string:

  1. {
  2. defaultValue: '__NOT_TRANSLATED__'
  3. }

Provides the default value as a callback function:

  1. {
  2. // @param {string} lng The language currently used.
  3. // @param {string} ns The namespace currently used.
  4. // @param {string} key The translation key.
  5. // @return {string} Returns a default value for the translation key.
  6. defaultValue: function(lng, ns, key) {
  7. if (lng === 'en') {
  8. // Return key as the default value for English language
  9. return key;
  10. }
  11. // Return the string '__NOT_TRANSLATED__' for other languages
  12. return '__NOT_TRANSLATED__';
  13. }
  14. }

resource

Type: Object

Resource options:

  1. { // Default
  2. resource: {
  3. // The path where resources get loaded from. Relative to current working directory.
  4. loadPath: 'i18n/{{lng}}/{{ns}}.json',
  5. // The path to store resources. Relative to the path specified by `gulp.dest(path)`.
  6. savePath: 'i18n/{{lng}}/{{ns}}.json',
  7. // Specify the number of space characters to use as white space to insert into the output JSON string for readability purpose.
  8. jsonIndent: 2,
  9. // Normalize line endings to '\r\n', '\r', '\n', or 'auto' for the current operating system. Defaults to '\n'.
  10. // Aliases: 'CRLF', 'CR', 'LF', 'crlf', 'cr', 'lf'
  11. lineEnding: '\n'
  12. }
  13. }

loadPath and savePath can be both be defined as Function with parameters lng and ns

  1. { // Default
  2. resource: {
  3. // The path where resources get loaded from. Relative to current working directory.
  4. loadPath: function(lng, ns) {
  5. return 'i18n/'+lng+'/'+ns+'.json';
  6. },
  7. // The path to store resources. Relative to the path specified by `gulp.dest(path)`.
  8. savePath: function(lng, ns) {
  9. return 'i18n/'+lng+'/'+ns+'.json';
  10. },
  11. // Specify the number of space characters to use as white space to insert into the output JSON string for readability purpose.
  12. jsonIndent: 2,
  13. // Normalize line endings to '\r\n', '\r', '\n', or 'auto' for the current operating system. Defaults to '\n'.
  14. // Aliases: 'CRLF', 'CR', 'LF', 'crlf', 'cr', 'lf'
  15. lineEnding: '\n'
  16. }
  17. }

keySeparator

Type: String or false Default: '.'

Key separator used in translation keys.

Set to false to disable key separator if you prefer having keys as the fallback for translation (e.g. gettext). This feature is supported by i18next@2.1.0. Also see Key based fallback at https://www.i18next.com/principles/fallback#key-fallback.

nsSeparator

Type: String or false Default: ':'

Namespace separator used in translation keys.

Set to false to disable namespace separator if you prefer having keys as the fallback for translation (e.g. gettext). This feature is supported by i18next@2.1.0. Also see Key based fallback at https://www.i18next.com/principles/fallback#key-fallback.

context

Type: Boolean or Function Default: true

Whether to add context form key.

  1. context: function(lng, ns, key, options) {
  2. return true;
  3. }

contextFallback

Type: Boolean Default: true

Whether to add a fallback key as well as the context form key.

contextSeparator

Type: String Default: '_'

The character to split context from key.

contextDefaultValues

Type: Array Default: []

A list of default context values, used when the scanner encounters dynamic value as a context.
For a list of ['male', 'female'] the scanner will generate an entry for each value.

plural

Type: Boolean or Function Default: true

Whether to add plural form key.

  1. plural: function(lng, ns, key, options) {
  2. return true;
  3. }

pluralFallback

Type: Boolean Default: true

Whether to add a fallback key as well as the plural form key.

pluralSeparator

Type: String Default: '_'

The character to split plural from key.

interpolation

Type: Object

interpolation options

  1. { // Default
  2. interpolation: {
  3. // The prefix for variables
  4. prefix: '{{',
  5. // The suffix for variables
  6. suffix: '}}'
  7. }
  8. }

metadata

Type: Object Default: {}

This can be used to pass any additional information regarding the string.

allowDynamicKeys

Type: Boolean Default: false

This can be used to allow dynamic keys e.g. friend${DynamicValue}

Example Usage:

  1. transform: function customTransform(file, enc, done) {
  2. 'use strict';
  3. const parser = this.parser;
  4. const contexts = {
  5. compact: ['compact'],
  6. max: ['Max'],
  7. };
  8. const keys = {
  9. difficulty: { list: ['Normal', 'Hard'] },
  10. minMax: { list: ['Min', 'Max'] },
  11. };
  12. const content = fs.readFileSync(file.path, enc);
  13. parser.parseFuncFromString(content, { list: ['i18next.t', 'i18n.t'] }, (key, options) => {
  14. // Add context based on metadata
  15. if (options.metadata?.context) {
  16. delete options.context;
  17. const context = contexts[options.metadata?.context];
  18. parser.set(key, options);
  19. for (let i = 0; i < context?.length; i++) {
  20. parser.set(`${key}${parser.options.contextSeparator}${context[i]}`, options);
  21. }
  22. }
  23. // Add keys based on metadata (dynamic or otherwise)
  24. if (options.metadata?.keys) {
  25. const list = keys[options.metadata?.keys].list;
  26. for (let i = 0; i < list?.length; i++) {
  27. parser.set(`${key}${list[i]}`, options);
  28. }
  29. }
  30. // Add all other non-metadata related keys
  31. if (!options.metadata) {
  32. parser.set(key, options);
  33. }
  34. });
  35. done();

Integration Guide

Checkout Integration Guide to learn how to integrate with React, Gettext Style I18n, and Handlebars.

License

MIT