Security News
Highlights from the 2024 Rails Community Survey
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
@ladjs/i18n
Advanced tools
@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.
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
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 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 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
npm:
npm install @ladjs/i18n
yarn:
yarn add @ladjs/i18n
const I18N = require('@ladjs/i18n');
const phrases = { 'HELLO': 'Hello there!' };
const i18n = new I18N({ phrases });
// ...
app.use(i18n.middleware);
app.use(i18n.redirect);
// ... routes go here ...
app.listen();
Returns translation for phrase key
with the given locale
. Optionally pass additional arguments, e.g. format specifier replacements for use in the phrase. For example if you have a phrase of "An error occurred %s" with a key of "ERROR_OCCURRED", and you use it as such i18n.translate('ERROR_OCCURRED', 'en', 'some error message')
then it would return 'An error occurred some error message
.
Returns the same string as i18n.translate
, but wrapped with a new Error
object with a property no_translate
set to true
.
This is an extremely useful method if you are using koa-better-error-handler
package in the Lad framework – as it will prevent a double translation from occurring.
This middleware uses custom locale detection (in order of priority):
/de
or /de/
then it's a de
locale - as long as de
is a supported locale)"locale"
cookie value (or whatever the cookie
option is defined as)Accept-Language
headerIt also exposes the following:
ctx.pathWithoutLocale
- the ctx.path
without the locale in it (this is used by koa-meta)ctx.request
- with all of i18n
API methods (e.g. ctx.request.t
, ctx.request.tn
, ...)ctx.locale
- set to the value of ctx.request.locale
(the current user's locale)ctx.state
- with all of i18n
API methods (e.g. ctx.request.t
, ctx.request.tn
, ...)ctx.state.l
- a shorthand method that accepts a path and returns a localized path (e.g. ctx.state.l('/contact')
will output /en/contact
if the locale is "en")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
methodctx.translate
(Function) - a helper function for calling i18n.api.t
or i18n.t
to translate a given phrase by its property key name from the phrases
object option (same as i18n.translate
except it throws a ctx.throw
error using Boom)ctx.translateError
(Function) - same as ctx.translate
except it returns an Error object with a property no_translate
set to true
(similar to i18n.translateError
)If the given locale was not available then it will redirect the user to the detected (or default/fallback) locale.
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.
NOTE: As of v1.2.2 we have added a ignoredRedirectGlobs
option you can pass to new I18N({ ... })
which will ignore these paths for locale redirection. This is incredibly useful if you are using authentication providers and the passport
library, e.g. you want to set /auth/github/ok
as the callback URL for GitHub, but a redirect to /en/auth/github/ok
would have occurred, thus causing authentication to fail due to a bad code. In this case, you would set { ignoredRedirectGlobs: [ '/auth/**/*' ] }
or simply [ '/auth/google/ok' ]
. This package uses multimatch internally which supports an Array, therefore you could negate certain paths if needed. See the documentation for multimatch for more insight.
It also sets the cookie locale
for future requests to their detected locale.
This also stores the last_locale
(or whatever you configure the property name to be in the config option lastLocaleField
) for a user via ctx.state.user.save()
.
NOTE: As of v3.0.0 we have added a redirectIgnoresNonGetMethods
(Boolean) option (defaults to true
) which you can pass to new I18N({ ... })
which will ignore non-GET methods on redirection.
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',
cookieOptions: {
// Disable signed cookies in NODE_ENV=test
signed: process.env.NODE_ENV !== 'test'
},
expiryMs: 31556952000, // one year in ms
indent: ' ',
defaultLocale: 'en',
// `process.env.I18N_SYNC_FILES`
syncFiles: true,
// `process.env.I18N_AUTO_RELOAD`
autoReload: false,
// `process.env.I18N_UPDATE_FILES`
updateFiles: true,
api: {
__: 't',
__n: 'tn',
__l: 'tl',
__h: 'th',
__mf: 'tmf'
},
register: i18n.api,
lastLocaleField: 'last_locale',
ignoredRedirectGlobs: [],
redirectIgnoresNonGetMethods: true,
// <https://github.com/ljharb/qs>
stringify: {
addQueryPrefix: true,
format: 'RFC1738',
arrayFormat: 'indices'
},
redirectTLDS: true
});
If you wish to bind logDebugFn
, logWarnFn
, and logErrorFn
per i18n options:
const i18n = new I18N({
logDebugFn: console.log,
logWarnFn: console.log,
logErrorFn: console.log
});
We recommend to use CabinJS for all your logging needs.
For a list of all available locales see i18n-locales.
If the path has an extension, then it is not redirected.
However if redirectTLDS
option is true
(which is true
by default as of v4.0.0), then if the path basename ends with a valid TLD, then it is redirected.
We came across this missing feature and added it after our discovery through Forward Email.
Name | Website |
---|---|
Nick Baugh | http://niftylettuce.com/ |
shadowgate15 | https://github.com/shadowgate15 |
FAQs
i18n wrapper and Koa middleware for Lad
The npm package @ladjs/i18n receives a total of 86,079 weekly downloads. As such, @ladjs/i18n popularity was classified as popular.
We found that @ladjs/i18n demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
Security News
In 2023, data breaches surged 78% from zero-day and supply chain attacks, but developers are still buried under alerts that are unable to prevent these threats.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.