Skip to content

shadowspawn/y18n

 
 

Repository files navigation

y18n

NPM version Conventional Commits

The bare-bones internationalization library used by yargs.

Inspired by i18n.

Examples

simple string translation:

import y18n from 'y18n';
const __ = y18n().__;

console.log(__('my awesome string %s', 'foo'));

output:

my awesome string foo

using tagged template literals

import y18n from 'y18n';
const __ = y18n().__;

const str = 'foo';

console.log(__`my awesome string ${str}`);

output:

my awesome string foo

pluralization support:

import y18n from 'y18n';
const __n = y18n().__n;

console.log(__n('one fish %s', '%d fishes %s', 2, 'foo'));

output:

2 fishes foo

Deno Example

As of v5 y18n supports Deno:

import y18n from 'https://deno.land/x/y18n/deno.ts';

const __ = y18n({
  locale: 'pirate',
  directory: './test/locales',
}).__;

console.info(__`Hi, ${'Ben'} ${'Coe'}!`);

You will need to run with --allow-read to load alternative locales.

JSON Language Files

The JSON language files should be stored in a ./locales folder. File names correspond to locales, e.g., en.json, pirate.json.

When strings are observed for the first time they will be added to the JSON file corresponding to the current locale.

Factory Function

The default export from y18n is a factory function. Use the function to create an instance of y18n. You may optionally supply configure options:

  • directory: the locale directory, default ./locales.
  • updateFiles: should newly observed strings be updated in file, default true.
  • locale: what locale should be used.
  • fallbackToLanguage: should fallback to a language-only file (e.g. en.json) be allowed if a file matching the locale does not exist (e.g. en_US.json), default true.

Methods

A y18n instance has the following methods.

__(str, arg, arg, arg)

Print a localized string, %s will be replaced with args.

This function can also be used as a tag for a template literal. You can use it like this: **`hello ${'world'}`. This will be equivalent to **('hello %s', 'world').

__n(singularString, pluralString, count, arg, arg, arg)

Print a localized string with appropriate pluralization. If %d is provided in the string, the count will replace this placeholder.

setLocale(str)

Set the current locale being used.

getLocale()

What locale is currently being used?

updateLocale(obj)

Update the current locale with the key value pairs in obj.

Supported Node.js Versions

Libraries in this ecosystem make a best effort to track Node.js' release schedule. Here's a post on why we think this is important.

License

ISC

About

📒 the bare-bones i18n library used by yargs

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

No packages published

Languages

  • JavaScript 60.0%
  • TypeScript 40.0%