The Simplest Universal i18n Solution
§ Preface
In most cases, internationalization is actually translating your website into English
Which means that you might not need a cumbersome framework to implement this
And this tiny repo is for you!
§ Features
- Support browsers and Node.js
- No dependencies (compressed source code < 0.5KB, extremely simple and comprehensible)
- Does not rely on any framework (React / Vue / Angular / ...) or any bundler (Webpack / Parcel / Rollup / ...)
- No tedious and verbose documentation (Just this README)
§ Installation
⊙ NPM
npm i simplest-i18n -S
⊙ CDN
<script src="//unpkg.com/simplest-i18n"></script>
§ Usage
const t = console // outputs 'Hello'
There are code examples for React and Vue in examples/
Check it out and run it with the following directives:
>_ git clone https://github.com/kenberkeley/simplest-i18n.git
>_ npm i
>_ npm run react (or npm run vue)
§ Merits
⊙ Keep in context
// this demonstrates how most popular i18n frameworks doconst messages = en: greeting: 'Hello {name}, long time no see' cn: greeting: '你好,{name},好久不见了' ja: greeting: 'こんにちは、{name}、長い時間は見ていない' *****************************************************************// in another file (lose direct sight of the original translations) { return <h1> </h1> }
// this is how we do with ES6 template literals { const name = thisstate return <h1> </h1> }
From now on, naming things and duplicate keys would not bother you anymore
(the key is actually the original text written in your mother tongue)
Before that, you might have to use a kinda nonsense module1.page1.greeting
(namespace) to avoid these problems
⊙ Flexible
How do we solve the pluralization problem?
- Method 0: Simple and crude: appending
(s) / (es)
directly
{ const num = thisstate return <span> </span> }
- Method 1: Write your own helper function
/** * @param * @param * @return * e.g. * pluralize('apple|apples', 3) => '3 apples' * pluralize('man|men', 1) => '1 man' */ { return ` `}
- Method 2: Search
plural
in npmjs.com and pick one
You can control everything in the project! No blackboxes! All functions are pure, simple and composable!
§ Tips
- If you are using Webpack and tired of importing
t
everywhere, try ProvidePlugin instead (window.t = t
is ok as you like it)