Message extraction
To extract all the messages that you want translated from your application code, a bit of setup is required.
Scripts
First, add scripts to your package.json
:
"scripts": {
...
"gettext:extract": "vue-gettext-extract",
"gettext:compile": "vue-gettext-compile",
}
npm run gettext:extract
extracts messages from your code and creates .po
files.
npm run gettext:compile
compiles the translated messages from the .po
files to a .json
to be used in your application.
Using these scripts is theoretically optional if you have other means of extraction or may even want to write message files yourself.
Configuration
Before running the scripts, create a file gettext.config.js
in your application root. This is a configuration only for the scripts above. A minimal configuration may look like this:
// @ts-check
/** @type {import('./src/index').Config} */
const config = {
output: {
locales: ["en", "de"],
},
};
export default config;
Here are all the available configuration options and their defaults:
// @ts-check
/** @type {import('./src/index').Config} */
const config = {
input: {
path: "./src", // only files in this directory are considered for extraction
include: ["**/*.js", "**/*.ts", "**/*.vue"], // glob patterns to select files for extraction
exclude: [], // glob patterns to exclude files from extraction
parserOptions: {
// add your own function names/keywords to extract
mapping: {
simple: ["$gettext"],
plural: ["$ngettext"],
ctx: ["$pgettext"],
ctxPlural: ["$npgettext"],
},
overrideDefaultKeywords: false, // do not extract default keywords, `mapping` must be set if this is enabled
},
},
output: {
path: "./src/language", // output path of all created files
potPath: "./messages.pot", // relative to output.path, so by default "./src/language/messages.pot"
jsonPath: "./translations.json", // relative to output.path, so by default "./src/language/translations.json"
locales: ["en"],
flat: true, // create a subdirectory for each locale
linguas: true, // create a LINGUAS file
splitJson: false, // create separate json files for each locale. If used, jsonPath must end with a directory, not a file
fuzzyMatching: true, // set if fuzzy matching should be enabled when merging the pot file into the po files
locations: true, // output location paths
},
};
export default config;
Gotchas
When first extract, it will call msginit
to create a .po
file, this command will set the Plural-Forms
header, if the locale is in the embedded table of msginit.
Otherwise, as an experimental feature, you can instruct msginit to use the information from Unicode CLDR, by setting the GETTEXTCLDRDIR
environment variable. The program will look for a file named common/supplemental/plurals.xml
under that directory. You can get the CLDR data from http://cldr.unicode.org/. Or only download the plurals.xml file.