babel-plugin-i18n
Efficient Multi-Language Text Translator for Babel.
How to use
Setup
Install it:
npm install --save-dev @joaofranciscosantos/babel-plugin-i18n
and add it to .babelrc as plugin:
{
"plugins": [["@joaofranciscosantos/babel-plugin-i18n"]]
}
Plugin Options
-
source
(array) the path of dictionary files. Defaults to.dictionary.json
. -
target
(string) function that is going to do the translation. Defaults toi18n
. -
language
(string) set the translation language. Defaults toen
.
{
"plugins": [["@joaofranciscosantos/babel-plugin-i18n", {
"source": ["translations/en.json", "dict.json"],
"language": "pt"
}]]
}
Dictionary
Must be a valid json file(s).
{
"keyword": {
"language": "translation"
},
"dog": {
"en": "dog",
"pt": "cão",
"es": "perro",
"it": "cane"
}
}
API
i18n(text: string, language: string) : string
-
text
text to translate. -
language
(optional) overrides the language set by the plugin.
Examples
-
i18n("dog", "es")
transpiles to"perro"
-
i18n("dog")
transpiles to"dog"
-
i18n("none", "?")
transpiles to"none"
- Because the source files do not provide a translation for the language
?
, it returns the original text.
- Because the source files do not provide a translation for the language
Tests
npm test
Use Cases
- Setup a different build for each language by setting the environment variable
BABEL_ENV
.
// .babelrc.js
module.exports = api => ({
'plugins': [['@joaofranciscosantos/babel-plugin-i18n', {
'language': api.env() // reads from process.env.BABEL_ENV
}]]
});