This may be the simplest i18n module for nodejs and the web.
locales/
├── en.json
├── en-US.json
├── kr.json
└── zh-CN.json
All locale files must be kept within one directory, with file extension
.json
and in json format.
yarn add node-i18n-core
# or
npm install node-i18n-core
import { I18n, II18nOption, IStorable, IListener } from 'node-i18n-core';
There are three options in II18nOption.
current
: the current locale.url
: an absolute path of file system or uri.loader
: an async function through which locale data is read asynchronously
There are two Loaders, one is FileSystemLoader
, the other is HTTPLoader
.
As their names imply, one is for file system, the other is for web served json files.
url
should be an absolute path
const options: II18nOption = {
current: 'en',
loader: FileSystemLoader,
url: path.resolve(__dirname, './locales/'),
};
url
should be an uri path where json files are served
const options: II18nOption = {
current: 'en',
loader: HTTPLoader,
url: 'http://www.yourdomain.com/xxx/locales/'
};
You can specify your storage or not.
const i18n = new I18n(options);
// Use windows.localStorage as the IStorable interface on the web
const i18n = new I18n(options, windows.localStorage);
To use translator, data must be initialized at first:
await i18n.init();
Now you have the json data prepared for access.
// Get Locale loaded from windows.localStorage
i18n.getLocale();
// Define an IStorable for yourself
const storage: IStorable = {
getItem: (key: string): string => {
return data[key];
},
setItem: (key: string, value: string): void => {
data[key] = value;
}
};
// Get Locale from a customzied IStorable instance
i18n.getLocale(storage);
// Set Locale to constructed storage
await i18n.setLocale('zh-CN');
// Set Locale to a temporay storage
await i18n.setLocale('zh-CN', storage);
// Listen the locale change infomation
const listener: IListener = (from, to) => {
console.log("locale has changed from: " + from + " to :" + to );
};
i18n.listen(listener);
// Get translated strings async
await i18n._('TITLE');
await i18n._('TITLE.SUBTITLE.SUBTITLE');
await i18n._('TITLE', 'zh-CN');
await i18n._('TITLE.SUBTITLE.SUBTITLE', 'ja');
// Get translated strings, no await need, return '' if not loaded or error.
i18n._sync('TITLE');
i18n._sync('TITLE.SUBTITLE.SUBTITLE');
i18n._sync('TITLE', 'zh-CN');
i18n._sync('TITLE.SUBTITLE.SUBTITLE', 'ja');