babel-plugin-i18n-replace
Replace i18n translation keys with their values during compilation using babel.
Supports flat and nested translation keys.
How it works
// application code // compile-time generated codetranslations // interpolation function to replace interpolation arguments at run-time// you will have to define it and can skip it if no interpolation is required // interpolates translation text at runtimeconst interpolate = { if !options return string; // support pluralization const replacement = string ? : string; return Object;}; // run-time result'Hello, John'
Check out example in webpack-integration example.
Installation
npm install --save-dev babel-plugin-i18n-replace
Usage
Checkout tests for usage examples.
Options
alias (string)
- function name to matchrelpaceWith (string)
- function name to replace withreturnKeyOnMissing (boolean)
- when translation key not found, use the key for valueallowStructures (boolean)
- allow numbers, hashes, etc instead of only strings as values - those will be converted to JSON stringstranslations (object)
- translations map
Via webpack (Recommended)
Checkout example application. It illustrates full application setup reading translations from json files and providing run-time interpolation support.
Via Node API
;
.babelrc
Via .babelrc
If you want to read translations from file, use webpack configuration.
Pluralization
Work with allowStructures: false
only.
Imagine we have the following pluralization keys:
We can determine run-time only which of these translations should be used,
so the plugin returns pluralize_##_{json_pluralization_options}
.
'pluralize_##_{"likes":{"one":"%{name} has %{count} like.","other":"%{name} has %{count} likes."}}'
Your interpolation function should handle this. See example application.
Limitations
-
New translations are only picked up on webpack server start as those are provided in webpack config.
-
Translation keys have to be static strings, as those are replaced with translated text compile-time. Interpolation (e.g. replacing
{name}
with current user name) should be performed run-time. This is achieved by replacing translation alias with an interpolation function.