Coder Social home page Coder Social logo

nano-i18n's Introduction

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 into ES & CJS format, 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 logging
  • 1 logs a warning in the console on a missing translation
  • 2 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:

  1. For the key, use a plain string with placeholders
  2. 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 of key/val pairs.

See also

Further reading

Other projects

nano-i18n's People

Contributors

danburzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nano-i18n's Issues

Add a webpack loader

Export a loader function that can be used for Webpack to get translations from an external file (e.g. CSV?) into a project. Should not be too opinionated on the structure it expects from the external files, and it's best that it works with other existing loaders.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.