Internationalization Library from the Simtopy Project
- JavaScript 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| conf | ||
| lib | ||
| src | ||
| tests | ||
| .gitignore | ||
| .gitlab-ci.yml | ||
| .jsbeautifyrc | ||
| index.js | ||
| LICENSE | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
Translator
Features
- Uses ES6 template literals for string formating.
- Provides utilities to extract labels from source files
- Provides utilities to read/write gettext (.po) files
- No dependencies
Usage example
Extraction from source code
import { extract, writePoFile} from "translator"
// LabelSet extraction
let labelset = extract("path/to/src/")
// LabelSet export
await writePoFile("path/to/loc/en.po", labelset)
Loading from translation files
/**
* server-side
*/
import { readPoFile } from "translator"
// the labelset can be read with the readPoFile function
let labelset = await readPoFile("path/to/loc/en.po")
// the labelset data can easily be serialized
app.get('/en', (req, res) => res.send(labelset.serialized))
/**
* client-side
*/
import Translator from "translator"
// the translator can be created from serialized data
let translator = Translator.fromSerializedData(data)
Creating label tags
Sometimes, you want to create a label without returning the translated string. This can be done with ease using the static Translator.label helper function :
import Translator from "translator"
Translator.label `returns a ${label}` // "returns a %0"
Translating strings
// source files should import the Translator
import Translator from "translator"
const localeContext = React.createContext(translator);
// Example in a React functional component
// the translator instance is usually in a provider
function Example(props) {
const {name, messages, gender} = props
const tr = useContext(localeContext)
// formated strings
const greeting = tr.translate `Hello ${name}` /* inline comment for the translator */
// pluralization
const messages = tr.agreeWith(messages) `${helloName}, you have ${messages} new message`
// custom agreement functions should return a variant index
function genderAgreement(gender) {
return gender === "male" ? 1 : 2
}
// simply add the agreement function as the second parameter
const amazing = tr.agreeWith(gender, genderAgreement) `${messages}, you are an amazing ${gender} !`
return <h1>amazing</h1>;
}
ChangeLog
0.4.1
- Added an option "template" to the toPoString function
- Added a writePOTfile function
0.4.0
- Pluaral forms now uses rules and are handled according to the gettext standard
0.3.3
- Now exposes a toPoString function in tools
0.3.2
- Merging labelsets should also override flags
0.3
- The regex should be used correctly to parse files
- Adding a unit test for the getFiles function
- Adding a changelog in the README