What is @ladjs/i18n?
@ladjs/i18n is a comprehensive internationalization (i18n) library for Node.js. It provides robust support for translating applications into multiple languages, managing locale data, and handling various localization needs. The package is designed to be flexible and easy to integrate into existing projects.
What are @ladjs/i18n's main functionalities?
Basic Translation
This feature allows you to set up basic translations for different locales. You can add translations for specific keys and retrieve the translated messages based on the current locale.
const I18n = require('@ladjs/i18n');
const i18n = new I18n();
// Set the locale
i18n.setLocale('en');
// Add translations
i18n.addTranslations('en', {
greeting: 'Hello'
});
// Translate a message
console.log(i18n.translate('greeting')); // Output: Hello
Dynamic Locale Switching
This feature demonstrates how to switch between different locales dynamically. You can add translations for multiple languages and change the locale at runtime to get the appropriate translations.
const I18n = require('@ladjs/i18n');
const i18n = new I18n();
// Add translations for multiple locales
i18n.addTranslations('en', { greeting: 'Hello' });
i18n.addTranslations('es', { greeting: 'Hola' });
// Switch locale dynamically
i18n.setLocale('es');
console.log(i18n.translate('greeting')); // Output: Hola
i18n.setLocale('en');
console.log(i18n.translate('greeting')); // Output: Hello
Pluralization Support
This feature shows how to handle pluralization in translations. You can define different messages for singular and plural forms and use the `count` variable to get the correct translation.
const I18n = require('@ladjs/i18n');
const i18n = new I18n();
// Add translations with pluralization
i18n.addTranslations('en', {
apple: {
one: 'one apple',
other: '{{count}} apples'
}
});
// Translate with pluralization
console.log(i18n.translate('apple', { count: 1 })); // Output: one apple
console.log(i18n.translate('apple', { count: 5 })); // Output: 5 apples
Other packages similar to @ladjs/i18n
i18next
i18next is a popular internationalization framework for JavaScript. It provides extensive support for translation, pluralization, and context-based translations. Compared to @ladjs/i18n, i18next offers more advanced features and a larger ecosystem of plugins and extensions.
polyglot
Polyglot is a lightweight internationalization library for JavaScript. It focuses on simplicity and ease of use, making it a good choice for smaller projects. While it lacks some of the advanced features of @ladjs/i18n, it is easier to set up and use for basic translation needs.
react-intl
react-intl is a library specifically designed for internationalizing React applications. It provides components and APIs for formatting dates, numbers, and strings based on locale. While it is more specialized than @ladjs/i18n, it offers seamless integration with React and a rich set of features for handling localization in React projects.
i18n wrapper and Koa middleware for Lad
Table of Contents
Install
npm:
npm install @ladjs/i18n
yarn:
yarn add @ladjs/i18n
Usage
const I18N = require('@ladjs/i18n');
const phrases = { 'HELLO': 'Hello there!' };
const i18n = new I18N({ phrases });
app.use(i18n.middleware);
app.use(i18n.redirect);
app.listen();
API
i18n.translate(key, locale)
Returns translation for phrase key
with the given locale
.
i18n.middleware(ctx, next)
This middleware uses custom locale detection (in order of priority):
- Check URL (e.g. if
/de
or /de/
then it's a de
locale - as long as de
is a supported locale) - Check the
"locale"
cookie value (or whatever the cookie
option is defined as) - Check
Accept-Language
header
It also exposes the following:
ctx.pathWithoutLocale
- the ctx.path
without the locale in it (this is used by koa-meta)ctx.req
- with all of i18n
API methods (e.g. ctx.req.t
, ctx.req.tn
, ...)ctx.state
- with all of i18n
API methods (e.g. ctx.req.t
, ctx.req.tn
, ...)ctx.state.availableLanguages
(Array) - which is useful for adding a dropdown to select from an available languagectx.state.currentLanguage
(String) - the current locale's language in native language using country-language's getLanguage
method.ctx.translate
(Function) - a helper function for calling i18n.api.t
to translate a given phrase (same as i18n.translate
except it throws a ctx.throw
error using Boom)
If the given locale was not available then it will redirect the user to the detected (or default/fallback) locale.
i18n.redirect(ctx, next)
Inspired by node's language support.
Redirects user with permanent 302
redirect to their detected locale if a valid language was not found for them.
It also sets the cookie locale
for future requests to their detected locale.
This also stores the last_locale
for a user via ctx.state.user.save()
.
Options
We use i18n options per https://github.com/mashpie/i18n-node#list-of-all-configuration-options
Default options are as follows and can be overridden:
const i18n = new I18N({
phrases: {},
logger: console,
directory: resolve('locales'),
locales: ['en', 'es', 'zh'],
cookie: 'locale',
indent: ' ',
defaultLocale: 'en',
syncFiles: true,
autoReload: true,
updateFiles: true,
api: {
__: 't',
__n: 'tn',
__l: 'tl',
__h: 'th',
__mf: 'tmf'
},
register: i18n.api
});
Note that we automatically bind logDebugFn
, logWarnFn
, and logErrorFn
for i18n options to logger.debug
, logger.warn
, and logger.error
respectively.
For a list of all available locales see i18n-locales.
Contributors
License
MIT © Nick Baugh