nano-i18n
v1.0.0
Published
Tiny experimental i18n library for JavaScript using tagged template literals.
Downloads
75
Maintainers
Readme
nano-i18n
nano-i18n
is a tiny experimental internationalization library for JavaScript, using tagged template literals.
Introduction
🔎 Internationalization (often abbreviated as i18n) is making sure a program can be adapted for several languages / cultures. It involves translating the words, but also using date, time, and number formats to which the people from a certain culture are accustomed.
nano-i18n
aims to offer a pleasant way of making your JavaScript app amenable to localization, without getting in the way too much. It focuses, for now, on translating strings.
Installation
nano-i18n
is packaged using microbundle into ES / CJS / UMD files, so it works in Node as well as browsers. You can also try out the API on RunKit without installing the library.
From the npm
registry
Install the library using npm
or yarn
:
# using npm
npm install nano-i18n
# using yarn
yarn add nano-i18n
As a <script>
tag
You can load the library directly in the browser as a <script>
tag, using unpkg. This will get you the latest version in the UMD module format:
<script src="https://unpkg.com/nano-i18n"></script>
Basic usage
To use nano-i18n
, you first need to load some translations into the store. We use the k
(from key) and v
(from value) tags to mark up our translations:
import { load, k, v } from 'nano-i18n';
// Load a key/value pair into the store
load(k`Hello, ${'World'}!`, v`Salut, ${0}!`);
Afterwards, translate strings with the t
tag:
import { t } from 'nano-i18n';
console.log(t`Hello, ${'Dan'}!`);
// => "Salut, Dan!"
API reference
Literal tags
📖 k
Obtains the key for a certain literal. By default, keys are obtained by replacing all interpolated values with the {}
character sequence:
import { k } from 'nano-i18n';
k`Hello, ${'World'}`;
// => "Hello, {}"
That means the strings you wish to translate must not otherwise contain the {}
sequence. You may change the placeholder with the config
method:
import { config } from 'nano-i18n';
config({
placeholder: '@@'
});
📖 v
Generates a translation function for a literal:
import { v } from 'nano-i18n';
v`Salut, ${0}!`;
// => function(strings, values) {}
When providing a translation, the interpolated values need to be numbers (i.e. ${0}
, ${1}
, et cetera). They don't necessarily need to be in sequential order. You can swap them around if the translation needs it:
import { k, v, t, load } from 'nano-i18n';
load(k`My name is ${0}, yours is ${1}`, v`Your name is ${1}, mine is ${0}`);
t`My name is ${'Dan'}, yours is ${'Alex'}`;
// "Your name is Alex, mine is Dan"
📖 t
Get a translated string:
import { t } from 'nano-i18n';
t`Hello, ${'Dan'}!`;
// => "Salut, Dan!"
If there's no translation available, it returns the normal interpolated string instead. The log
config option controls how the library reports missing translations.
Managing the store
📖 load(key: string, value: string | function)
The load method adds translations to the store.
You can add the translations one by one:
import { load, k, v } from 'nano-i18n';
load(k`Hello, ${'World'}!`, v`Salut, ${0}!`);
Or a whole batch of translations:
import { load, k, v } from 'nano-i18n';
let translations = {};
translations[k`Hello, ${'World'}!`] = v`Salut, ${0}!`;
translations[k`My name is ${'name'}`] = v`Numele meu este ${0}`;
load(translations);
Or using the computed property names syntax:
import { load, k, v } from 'nano-i18n';
load({
[k`Hello, ${'World'}!`]: v`Salut, ${0}!`,
[k`My name is ${'name'}`]: v`Numele meu este ${0}`
});
Or skipping the k
literal tag altogether and using a string key directly:
import { load } from 'nano-i18n';
load('Hello, {}!', v`Salut, ${0}!`);
You can also skip the v
literal tag and send a simple string translation:
import { load } from 'nano-i18n';
load('Hello, World!', 'Salut, lume!');
📖 clear()
The clear
method removes all the translations from the store.
import { clear } from 'nano-i18n';
clear();
📖 config(options: object)
Configures the library. Available options:
log: number | function, default 0
The log level for the library. Possible values:
0
disables logging1
logs a warning in the console on a missing translation2
throws an error when encountering a missing translation
You can also set up a custom logging function, in case you want to keep track of exceptions some other way:
import { config } from 'nano-i18n';
config({
log: function (message, key) {
/*
You could do something with `message`,
e.g. send the error to Sentry.
`key` contains just the key the message
refers to.
*/
}
});
placeholder: string, default {}
The string to use as placeholder for interpolated values when generating the key for a translation.
Usage with templating languages
You may be working with a templating language, such as Mustache or its variants, that does not support tagged template literals in its syntax. The good news is that tags in general, and the t
tag in particular, can also be used as a plain function:
import { t } from 'nano-i18n';
t('Hello, World!');
// => 'Salut, lume!'
To use string interpolation with the t()
function:
- For the key, use a plain string with placeholders
- Pass the values as extra arguments to the function
t('My name is {}, yours is {}', 'Dan', 'Alex');
Look in your templating language's API reference for the specifics of passing, and using, functions in templates.
Usage with Webpack
This library can be used with Webpack to load translations from external files with the nano-i18n/loader
loader. nano-i18n
comes with the loader, so you don't have to install any other packages.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.json$/,
include: /locales/,
loader: 'nano-i18n/loader'
}
]
}
};
By default, external files are expected to be JSONs containing an array of key
/val
pairs, i.e.:
locales/ro-RO.json
[
{ key: "Hello, ${'World'}", val: 'Salut, ${0}' },
{ key: 'Some String', val: 'Un Șir Oarecare' }
// etc.
];
With this setup in place, we can load the JSON as ready-to-use translations:
import { load } from 'nano-i18n';
load(require('path/to/locales/ro-RO.json'));
nano-i18n/loader
also accepts a parse
option with you can use to keep the external translation files in any format, as long as you format it to key
/val
pairs.
Let's say you want to keep the translations in a CSV file so that it's easy to edit them in Microsoft Excel or macOS Numbers:
locales/ro-RO.csv
"key","val"
"Hello, ${'World'}","Salut, ${0}"
"Some String","Un Șir Oarecare"
In our Webpack configuration, we'll parse the CSV file using the d3-dsv
package:
webpack.config.js
let { csvParse } = require('d3-dsv');
module.exports = {
module: {
rules: [
{
test: /\.csv$/,
include: /locales/,
loader: 'nano-i18n/loader',
options: {
parse: text => csvParse(text)
}
}
]
}
};
💡 The
parse
option accepts a function which receives as its only argument the original text to parse, and which must return an array ofkey
/val
pairs.
See also
Further reading
- i18n with tagged template literals in ECMAScript 2015 by Jack Hsu
- Easy i18n in 10 lines of JavaScript (PoC) by Andrea Giammarchi
Other projects
- i18n Tagged Template Literals by Steffen Kolmer
- ttag