Top Related Projects
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
i18next: learn once - translate everywhere
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
๐ ๐ A readable, automated, and optimized (2 kb) internationalization for JavaScript
:globe_with_meridians: Internationalization plugin for Vue.js
Quick Overview
Polyglot.js is a lightweight JavaScript library for internationalization (i18n) in web applications. It provides a simple and flexible way to manage translations and pluralization for multiple languages, making it easier to create multilingual websites and applications.
Pros
- Easy to use and integrate into existing projects
- Supports pluralization and interpolation
- Lightweight with no external dependencies
- Compatible with both browser and Node.js environments
Cons
- Limited features compared to more comprehensive i18n libraries
- Lacks built-in support for date and number formatting
- No automatic language detection
- Documentation could be more extensive
Code Examples
- Basic translation:
import Polyglot from 'polyglot.js';
const polyglot = new Polyglot({ phrases: {
"hello": "Hello",
"hello_name": "Hello, %{name}"
}});
console.log(polyglot.t("hello")); // Output: "Hello"
console.log(polyglot.t("hello_name", { name: "John" })); // Output: "Hello, John"
- Pluralization:
const polyglot = new Polyglot({ phrases: {
"num_cars": "%{smart_count} car |||| %{smart_count} cars"
}});
console.log(polyglot.t("num_cars", { smart_count: 1 })); // Output: "1 car"
console.log(polyglot.t("num_cars", { smart_count: 2 })); // Output: "2 cars"
- Changing language:
const polyglot = new Polyglot();
polyglot.extend({
"hello": "Hello",
"goodbye": "Goodbye"
});
console.log(polyglot.t("hello")); // Output: "Hello"
polyglot.replace({
"hello": "Bonjour",
"goodbye": "Au revoir"
});
console.log(polyglot.t("hello")); // Output: "Bonjour"
Getting Started
- Install Polyglot.js:
npm install node-polyglot
- Import and initialize Polyglot:
import Polyglot from 'node-polyglot';
const polyglot = new Polyglot();
polyglot.extend({
"hello": "Hello",
"goodbye": "Goodbye"
});
- Use translations in your code:
console.log(polyglot.t("hello")); // Output: "Hello"
Competitor Comparisons
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
Pros of FormatJS
- More comprehensive internationalization (i18n) solution with support for various formats (dates, numbers, plurals)
- Integrates well with popular frameworks like React and Angular
- Actively maintained with frequent updates and a larger community
Cons of FormatJS
- Steeper learning curve due to more complex API and features
- Larger bundle size, which may impact performance for smaller projects
- Requires more setup and configuration compared to simpler alternatives
Code Comparison
Polyglot.js:
var polyglot = new Polyglot();
polyglot.extend({"hello": "Hello"});
polyglot.t("hello");
FormatJS:
import { IntlProvider, FormattedMessage } from 'react-intl';
<IntlProvider messages={{"hello": "Hello"}}>
<FormattedMessage id="hello" />
</IntlProvider>
Summary
FormatJS offers a more feature-rich i18n solution with better framework integration, while Polyglot.js provides a simpler, lightweight alternative. FormatJS is ideal for larger projects requiring advanced internationalization features, whereas Polyglot.js may be more suitable for smaller projects or those needing a quick, easy-to-implement solution. The choice between the two depends on the specific requirements of your project, development ecosystem, and performance considerations.
i18next: learn once - translate everywhere
Pros of i18next
- More comprehensive and feature-rich, supporting advanced localization scenarios
- Extensive plugin ecosystem for various frameworks and platforms
- Better support for pluralization and context-based translations
Cons of i18next
- Steeper learning curve due to its extensive feature set
- Potentially overkill for simple localization needs
- Larger bundle size compared to Polyglot.js
Code Comparison
i18next:
import i18next from 'i18next';
i18next.init({
lng: 'en',
resources: {
en: {
translation: {
key: 'Hello, {{name}}!'
}
}
}
});
console.log(i18next.t('key', { name: 'World' }));
Polyglot.js:
import Polyglot from 'node-polyglot';
const polyglot = new Polyglot();
polyglot.extend({
en: {
hello: 'Hello, %{name}!'
}
});
console.log(polyglot.t('hello', { name: 'World' }));
Both libraries provide similar basic functionality for internationalization, but i18next offers more advanced features and flexibility at the cost of complexity. Polyglot.js is simpler and more lightweight, making it suitable for smaller projects with basic localization needs.
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
Pros of FormatJS
- More comprehensive internationalization (i18n) solution with support for various formats (dates, numbers, plurals)
- Integrates well with popular frameworks like React and Angular
- Actively maintained with frequent updates and a larger community
Cons of FormatJS
- Steeper learning curve due to more complex API and features
- Larger bundle size, which may impact performance for smaller projects
- Requires more setup and configuration compared to simpler alternatives
Code Comparison
Polyglot.js:
var polyglot = new Polyglot();
polyglot.extend({"hello": "Hello"});
polyglot.t("hello");
FormatJS:
import { IntlProvider, FormattedMessage } from 'react-intl';
<IntlProvider messages={{"hello": "Hello"}}>
<FormattedMessage id="hello" />
</IntlProvider>
Summary
FormatJS offers a more feature-rich i18n solution with better framework integration, while Polyglot.js provides a simpler, lightweight alternative. FormatJS is ideal for larger projects requiring advanced internationalization features, whereas Polyglot.js may be more suitable for smaller projects or those needing a quick, easy-to-implement solution. The choice between the two depends on the specific requirements of your project, development ecosystem, and performance considerations.
๐ ๐ A readable, automated, and optimized (2 kb) internationalization for JavaScript
Pros of js-lingui
- More comprehensive internationalization solution with support for plurals, gender, and complex message formatting
- Offers a CLI tool for extracting messages and managing translations
- Integrates well with React and provides optimized components for translation
Cons of js-lingui
- Steeper learning curve due to more complex API and concepts
- Requires additional setup and configuration compared to simpler solutions
- May be overkill for projects with basic translation needs
Code Comparison
js-lingui:
import { Trans } from '@lingui/macro'
function Welcome({ name }) {
return <Trans>Hello, {name}!</Trans>
}
Polyglot.js:
const polyglot = new Polyglot();
polyglot.extend({ "hello": "Hello, %{name}!" });
function welcome(name) {
return polyglot.t("hello", { name: name });
}
Key Differences
- js-lingui provides a more React-friendly approach with components and macros
- Polyglot.js offers a simpler API for basic translation needs
- js-lingui supports more complex message formatting out of the box
- Polyglot.js is lighter and easier to set up for small projects
Both libraries serve different use cases, with js-lingui being more suitable for larger, complex applications with extensive i18n requirements, while Polyglot.js is better for simpler projects needing basic translation functionality.
:globe_with_meridians: Internationalization plugin for Vue.js
Pros of vue-i18n
- Specifically designed for Vue.js, offering seamless integration with Vue components
- Supports pluralization and date/time localization out of the box
- Provides a more comprehensive i18n solution with features like lazy loading and custom formatting
Cons of vue-i18n
- Limited to Vue.js ecosystem, not suitable for non-Vue projects
- Steeper learning curve due to more advanced features and Vue-specific concepts
Code Comparison
vue-i18n:
const i18n = new VueI18n({
locale: 'en',
messages: {
en: { hello: 'Hello' },
ja: { hello: 'ใใใซใกใฏ' }
}
})
polyglot.js:
const polyglot = new Polyglot();
polyglot.extend({
en: { hello: 'Hello' },
ja: { hello: 'ใใใซใกใฏ' }
});
Both libraries provide similar basic functionality for internationalization, but vue-i18n is more tightly integrated with Vue.js and offers additional features specific to the Vue ecosystem. polyglot.js, on the other hand, is more lightweight and framework-agnostic, making it suitable for a wider range of JavaScript projects beyond Vue.js applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Polyglot.js
Polyglot.js is a tiny I18n helper library written in JavaScript, made to work both in the browser and in CommonJS environments (Node). It provides a simple solution for interpolation and pluralization, based off of Airbnbรขยยs experience adding I18n functionality to its Backbone.js and Node apps.
I18n is incredibly important for us at Airbnb, as we have listings in 192 countries, and we translate our site into 30-odd different languages. Weรขยยre also hiring talented engineers to help us scale up to meet the challenges of building a global marketplace.
View the documentation on Github.
View the annotated source.
Polyglot is agnostic to your translation backend. It doesnรขยยt perform any translation; it simply gives you a way to manage translated phrases from your client- or server-side JavaScript application.
Installation
install with npm:
$ npm install node-polyglot
Running the tests
Clone the repo, run npm install
, and npm test
.
Usage
Instantiation
First, create an instance of the Polyglot
class, which you will use for translation.
var polyglot = new Polyglot();
Polyglot is class-based so you can maintain different sets of phrases at the same time, possibly in different locales. This is very useful for example when serving requests with Express, because each request may have a different locale, and you donรขยยt want concurrent requests to clobber each otherรขยยs phrases.
See Options Overview for information about the options object you can choose to pass to new Polyglot
.
Translation
Tell Polyglot what to say by simply giving it a phrases object, where the key is the canonical name of the phrase and the value is the already-translated string.
polyglot.extend({
"hello": "Hello"
});
polyglot.t("hello");
=> "Hello"
You can also pass a mapping at instantiation, using the key phrases
:
var polyglot = new Polyglot({phrases: {"hello": "Hello"}});
Polyglot doesnรขยยt do the translation for you. Itรขยยs up to you to give it the proper phrases for the userรขยยs locale.
A common pattern is to gather a hash of phrases in your backend, and output
them in a <script>
tag at the bottom of the document. For example, in Rails:
app/controllers/home_controller.rb
def index
@phrases = {
"home.login" => I18n.t("home.login"),
"home.signup" => I18n.t("home.signup"),
...
}
end
app/views/home/index.html.erb
<script>
var polyglot = new Polyglot({phrases: <%= raw @phrases.to_json %>});
</script>
And now you can utilize i.e. polyglot.t("home.login")
in your JavaScript application
or Handlebars templates.
Interpolation
Polyglot.t()
also provides interpolation. Pass an object with key-value pairs of
interpolation arguments as the second parameter.
polyglot.extend({
"hello_name": "Hola, %{name}."
});
polyglot.t("hello_name", {name: "DeNiro"});
=> "Hola, DeNiro."
Polyglot also supports nested phrase objects.
polyglot.extend({
"nav": {
"hello": "Hello",
"hello_name": "Hello, %{name}",
"sidebar": {
"welcome": "Welcome"
}
}
});
polyglot.t("nav.sidebar.welcome");
=> "Welcome"
The substitution variable syntax is customizable.
var polyglot = new Polyglot({
phrases: {
"hello_name": "Hola {{name}}"
},
interpolation: {prefix: '{{', suffix: '}}'}
});
polyglot.t("hello_name", {name: "DeNiro"});
=> "Hola, DeNiro."
Pluralization
For pluralization to work properly, you need to tell Polyglot what the current locale is. You can use polyglot.locale("fr")
to set the locale to, for example, French. This method is also a getter:
polyglot.locale()
=> "fr"
You can also pass this in during instantiation.
var polyglot = new Polyglot({locale: "fr"});
Currently, the only thing that Polyglot uses this locale setting for is pluralization.
Polyglot provides a very basic pattern for providing pluralization based on a single string that contains all plural forms for a given phrase. Because various languages have different nominal forms for zero, one, and multiple, and because the noun can be before or after the count, we have to be overly explicit about the possible phrases.
To get a pluralized phrase, still use polyglot.t()
but use a specially-formatted phrase string that separates the plural forms by the delimiter ||||
, or four vertical pipe characters.
For pluralizing "car" in English, Polyglot assumes you have a phrase of the form:
polyglot.extend({
"num_cars": "%{smart_count} car |||| %{smart_count} cars",
});
Please keep in mind that smart_count
is required. No other option name is taken into account to transform pluralization strings.
In English (and German, Spanish, Italian, and a few others) there are only two plural forms: singular and not-singular.
Some languages get a bit more complicated. In Czech, there are three separate forms: 1, 2 through 4, and 5 and up. Russian is even more involved.
var polyglot = new Polyglot({locale: "cs"}); // Czech
polyglot.extend({
"num_foxes": "Mรยกm %{smart_count} liร
ยกku |||| Mรยกm %{smart_count} liร
ยกky |||| Mรยกm %{smart_count} liร
ยกek"
})
polyglot.t()
will choose the appropriate phrase based on the provided smart_count
option, whose value is a number.
polyglot.t("num_cars", {smart_count: 0});
=> "0 cars"
polyglot.t("num_cars", {smart_count: 1});
=> "1 car"
polyglot.t("num_cars", {smart_count: 2});
=> "2 cars"
As a shortcut, you can also pass a number to the second parameter:
polyglot.t("num_cars", 2);
=> "2 cars"
Custom Pluralization Rules
Polyglot provides some default pluralization rules for some locales. You can specify a different set of rules through the pluralRules
constructor param.
var polyglot = new Polyglot({
pluralRules: {
pluralTypes: {
germanLike: function (n) {
// is 1
if (n === 1) {
return 0;
}
// everything else
return 1;
},
frenchLike: function (n) {
// is 0 or 1
if (n <= 1) {
return 0;
}
// everything else
return 1;
}
},
pluralTypeToLanguages: {
germanLike: ['de', 'en', 'xh', 'zu'],
frenchLike: ['fr', 'hy']
}
}
});
This can be useful to support locales that polyglot does not support by default or to change the rule definitions.
Public Instance Methods
Polyglot.prototype.t(key, interpolationOptions)
The most-used method. Provide a key, and t()
will return the phrase.
polyglot.t("hello");
=> "Hello"
The phrase value is provided first by a call to polyglot.extend()
or polyglot.replace()
.
Pass in an object as the second argument to perform interpolation.
polyglot.t("hello_name", {name: "Spike"});
=> "Hello, Spike"
Pass a number as the second argument as a shortcut to smart_count
:
// same as: polyglot.t("car", {smart_count: 2});
polyglot.t("car", 2);
=> "2 cars"
If you like, you can provide a default value in case the phrase is missing. Use the special option key "_" to specify a default.
polyglot.t("i_like_to_write_in_language", {
_: "I like to write in %{language}.",
language: "JavaScript"
});
=> "I like to write in JavaScript."
Polyglot.prototype.extend(phrases)
Use extend
to tell Polyglot how to translate a given key.
polyglot.extend({
"hello": "Hello",
"hello_name": "Hello, %{name}"
});
The key can be any string. Feel free to call extend
multiple times; it will override any phrases with the same key, but leave existing phrases untouched.
Polyglot.prototype.unset(keyOrObject)
Use unset
to selectively remove keys from a polyglot instance.
unset
accepts one argument: either a single string key, or an object whose keys are string keys, and whose values are ignored unless they are nested objects (in the same format).
Example:
polyglot.unset('some_key');
polyglot.unset({
hello: 'Hello',
hello_name: 'Hello, %{name}',
foo: {
bar: 'This phraseรขยยs key is "foo.bar"'
}
});
Polyglot.prototype.locale([localeToSet])
Get or set the locale (also can be set using the constructor option, which is used only for pluralization. If a truthy value is provided, it will set the locale. Afterwards, it will return it.
Polyglot.prototype.clear()
Clears all phrases. Useful for special cases, such as freeing up memory if you have lots of phrases but no longer need to perform any translation. Also used internally by replace
.
Polyglot.prototype.replace(phrases)
Completely replace the existing phrases with a new set of phrases.
Normally, just use extend
to add more phrases, but under certain circumstances, you may want to make sure no old phrases are lying around.
Polyglot.prototype.has(key)
Returns true
if the key does exist in the provided phrases, otherwise it will return false
.
Public Static Methods
transformPhrase(phrase[, substitutions[, locale]])
Takes a phrase string and transforms it by choosing the correct plural form and interpolating it. This method is used internally by t.
The correct plural form is selected if substitutions.smart_count is set.
You can pass in a number instead of an Object as substitutions
as a shortcut for smart_count
.
You should pass in a third argument, the locale, to specify the correct plural type. It defaults to 'en'
which has 2 plural forms.
Options Overview
new Polyglot
accepts a number of options:
phrases
: a key/value map of translated phrases. See Translation.locale
: a string describing the locale (language and region) of the translation, to apply pluralization rules. see PluralizationallowMissing
: a boolean to control whether missing keys in at
call are allowed. Iffalse
, by default, a missing key is returned and a warning is issued.onMissingKey
: ifallowMissing
istrue
, and this option is a function, then it will be called instead of the default functionality. Arguments passed to it arekey
,options
, andlocale
. The return of this function will be used as a translation fallback whenpolyglot.t('missing.key')
is called (hint: return the key).interpolation
: an object to change the substitution syntax for interpolation by setting theprefix
andsuffix
fields.pluralRules
: an object ofpluralTypes
andpluralTypeToLanguages
to control pluralization logic.
History
Related projects
- i18n-extract: Manage localization with static analysis. (E.g. key usage extraction)
Top Related Projects
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
i18next: learn once - translate everywhere
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
๐ ๐ A readable, automated, and optimized (2 kb) internationalization for JavaScript
:globe_with_meridians: Internationalization plugin for Vue.js
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot