-
Notifications
You must be signed in to change notification settings - Fork 21
Introduction
Let's start with an example of how this library can be used. The details are explained below.
const { GettextExtractor, JsExtractors, HtmlExtractors } = require('gettext-extractor');
let extractor = new GettextExtractor();
extractor
.createJsParser([
JsExtractors.callExpression('getText', {
arguments: {
text: 0,
context: 1
}
}),
JsExtractors.callExpression('getPlural', {
arguments: {
text: 1,
textPlural: 2,
context: 3
}
})
])
.parseFilesGlob('./src/**/*.@(ts|js|tsx|jsx)');
extractor
.createHtmlParser([
HtmlExtractors.elementContent('translate, [translate]')
])
.parseFilesGlob('./src/**/*.html');
extractor.savePotFile('./messages.pot');
extractor.printStats();
First of all we have to import this package. Unfortunately ES6 modules aren't supported by Node.js yet, but we can use deconstruction to the two imports we need. Of course doing var lib = require('gettext-extractor');
works as well.
Note: If you use an ES6 transpiler you can of course go for the nicer syntax:
import { GettextExtract, JsExtractors, HtmlExtractors } from 'gettext-extractor';
To get started we create a GettextExtractor
instance. This object gathers extracted messages and in the end saves them as template for translations.
You may create multiple instances, which can be useful if you want to separate your strings into different .pot
files.
Note: Extracted strings are called messages in Gettext terminology (sometimes they are incorrectly referred to as translations).
Now we create a JavaScript and HTML parser with createJsParser()
and createHtmlParser()
and pass in an array of extractor functions.
Extractor functions are responsible for finding and extracting translatable strings.
They are called for every node in the AST and add strings they find to the message catalog.
If this sounds complicated to you, don't worry! In most cases you don't actually have to write an extractor function yourself. This library includes factories to create extractor functions, but still allow you a lot of control over what they extract.
For more details refer to the JavaScript, TypeScript, JSX and HTML sections.
All the configuration is done and we can get started with parsing. The method parseFilesGlob
let's us pass in a glob pattern and runs all files that match through the parser to extract messages. There are other methods for parsing a single file or just a string as well. All of them are documented in the API Reference.
With savePotFile()
all extracted messages are written to the specified .pot
file in Gettext format. If you'd like to save the file async, you may use savePotFileAsync
which returns a promise.
And finally, printStats()
writes statistics about all extracted messages to the console.
Read more in the Statistics section.
Getting Started
Languages