@sysdoc/localization
v1.0.1
Published
Sysdoc's core localization service
Downloads
4
Keywords
Readme
Sysdoc's i18n localization utility
Installation
npm install @sysdoc/localization node-polyglot
Introduction
This package contains the core localization functionality for Sysdoc's i18n setup ontop of AirBnB's node-polyglot (https://github.com/airbnb/polyglot.js#readme) library.
It requires that you setup an object which contains your localized phrases, instantiate a new Polyglot with the phrases and the name of the locale then assign it to Sysdoc global namespace under window.Sysdoc.Locale.Polyglot
.
An example of a configured locale file can be found below:
import * as PolyGlot from "node-polyglot";
const Locale = {
loading: ["Working, one moment..."],
phrases: {
complete: "Complete",
draft: "Draft",
faqs: "FAQs",
helloWorld: "Hello World!",
helpFaqs: "Help and FAQs",
quickGuide: "Quick Guide",
runAReport: "Run a report",
submitted: "Submitted",
view: "View",
viewMore: "View More"
}
};
window.Sysdoc = window.Sysdoc || {};
window.Sysdoc.Locale = window.Sysdoc.Locale || {};
window.Sysdoc.Locale.Data = Locale;
const polyglot = new PolyGlot();
polyglot.locale("en-US");
polyglot.extend(Locale);
window.Sysdoc.Locale.Polyglot = polyglot;
Use
In order to use the localization functionality you would do the following:
import {
createDefaultI18nLocalizer,
I18nLocalizer
} from "@sysdoc/localization";
const i18n: I18nLocalizer = createDefaulti18nLocalizer();
You can then pass this through your application however you would like i.e. you could extend from a Base Model in an object oriented paradigm or pass the object around a React application using the Context API or some other global state management solution.
To use the localization library with the React Context API do the following...
Define a context in a LocaleContext file:
import * as React from "react";
import { I18nLocalizer } from "@sysdoc/localization";
// We need to pass createContext a partial of the I18nLocalizer interface here in order to get intellisense and typing.
export const LocaleContext = React.createContext<Partial<I18nLocalizer>>({});
Provide the context to the app with the localizer:
import * as React from "react";
import {
createDefaultI18nLocalizer,
I18nLocalizer
} from "@sysdoc/localization";
import { LocaleContext } from "./LocaleContext";
import { App } from "./App";
const i18n: I18nLocalizer = createDefaulti18nLocalizer();
const AppWrapper = () => (
<LocaleContext.Provider value={i18n}>
<App />
</LocaleContext.Provider>
);
Consume the context inside the app:
import * as React from "react";
import { App } from "./App";
import { LocaleContext } from "./LocaleContext";
export const App = () => {
const i18n = React.useContext(LocaleContext);
return <div>{i18n.format("phrases.helloWorld")}</div>;
};
The expected output if using the en-US locale defined above is: <div>Hello World!</div>