JavaScript Apps Internationalization
In this tutorial, we'll learn how to use Lingui's internationalization features that don't depend on React. We'll take a minimalist approach and cover the main features of the @lingui/core
package.
Installing Lingui
- Follow the Installation and Setup page for initial setup.
- Install the
@lingui/core
package, which is responsible for translation and handling of message catalogs.
Setting up i18n
First we need to setup the i18n singleton, which is pretty simple:
import { i18n } from "@lingui/core";
// messages.js is generated by the cli
import { messages } from "path-to-locale/en/messages.js";
i18n.load("en", messages);
i18n.activate("en");
Localizing Your App
Once that is done, we can go ahead and use it! Wrap your text in t
macro:
import { t } from "@lingui/core/macro";
t`Hello World!`;
// becomes "Salut le monde!"
const name = "Fred";
t`My name is ${name}`;
// becomes "Je m'appelle Fred"
Plurals and selections are possible using plural and select methods:
import { plural } from "@lingui/core/macro";
const count = 42;
plural(count, {
one: "# book",
other: "# books",
});
// becomes "42 livres"
It's also possible to nest message formats. Each message format method in i18n has a standalone companion, which only returns message without performing the translation:
import { t, select, plural } from "@lingui/core/macro"
select(gender, {
offset: 1,
female: plural(numOfGuests, {
offset: 1,
0: t`${host} does not give a party.`,
1: t`${host} invites ${guest} to her party.`,
2: t`${host} invites ${guest} and one other person to her party.`,
other: t`${host} invites ${guest} and # other people to her party.`
}),
male: plural(value, {...}),
other: plural(value, {...}),
})