Preact internationalization, done simply.
npm install preact-i18n
Simple localization for Preact.
- Tiny: about 1.3kb gzipped
- Supports dictionary and key scopes/namespaces while maintaining a global dictionary
- Supports nested dictionaries:
- Wrap your component in a default dictionary and scope key
- Wrap it again later on (in an app!) to override the defaults
- Supports pluralization of strings using nested objects.
- Supports template {{fields}} in definition values
- Has a companion ESLint plugin to help catch bugs early
*
- Installation
- Getting Started
- Fallback Text
- Pluralization and Templating
- ESLint Plugin
- API
By default, the master branch of this repo supports preact 9 and below, and is published in normal patch/minor/major releases to the latest tag in npm. Support for preact X (versions 10+ of preact) is handled in the preactX branch and are always published to the preactx tag in npm. When preact X obtains widespread adoption, the master branch of this project will support preact X and a new major version under latest tag will be published to in npm.
``sh
npm install --save preact-i18n
Getting Started
1. Create a definition. Typically JSON files, we'll call ours
fr.json:`json
{
"news": {
"title": "Nouvelles du Monde",
"totalStories": {
"none": "Aucun article",
"one": "Un article",
"many": "{{count}} articles"
}
}
}
`2. Expose the definition to your whole app via
:`js
import { IntlProvider } from 'preact-i18n';
import definition from './fr.json';render(
);
`3. Use
to translate string literals:`js
import { Text } from 'preact-i18n';// Assume the "stories" prop is a list of news stories.
const App = ({ stories=[] }) => (
{/ Default fallback text example: /}
World News
);
`That's it!
$3
Rendering our example app with an empty definition _(or without the Provider)_ will attempt to use any text contained within
as fallback text.In our example, this would mean rendering without a definition for
news.title would produce .If we provide a definition that has a
title key inside a news object, that value will be rendered instead.$3
In our example,