svelte-i18n-gettext

1.0.10 • Public • Published

svelte-i18n-gettext

License GitHub all releases GitHub issues GitHub commit activity

This is a Svelte component based on derived stores which implements gettext based translation (i18n) of strings.

Usage

  • Install package (published here).
npm install svelte-i18n-gettext
  • Include the stores:
import { _, _n } from 'svelte-i18n-gettext/src/index.svelte';
import { parsedTranslations, lang } from 'svelte-i18n-gettext/src/store.js';
  • Use the lang (or a local alias) store to specify the language to use:
$lang = 'es-MX';
  • Optionally, get the browser's language:
$lang = detectBrowserLanguage();	

Or any other method, such as loading user's preferences.

  • Include the translation files (see the examples directory for samples) and assign them to the store:

    import msg_de_DE from '$lib/i18n/messages-de.json';
    $parsedTranslations['de-DE'] = msg_de_DE;
    
    import msg_en_US from '$lib/i18n/messages-en.json';
    $parsedTranslations['en-US'] = msg_en_US;
    
    import msg_es_MX from '$lib/i18n/messages-es.json';
    $parsedTranslations['es-MX'] = msg_es_MX;	

    (Adjust your paths according to your project's structure)

  • In your Svelte code, for singular form you can use the $_ derived store:

<div>
    {@html $_(`Welcome, <b>${$user.profile.name}</b>`)}
    <br />
    {$_("Good bye.")}
</div>
  • In your Svelte code, for plural forms you can use the $_n derived store:
<div>
    <!-- n contains the number of deleted files -->
    {@html $_n(`One file deleted`, `${n} files deleted`, n)}
</div>

These stores have the following signatures:

_(msgid, msgctx)
_n(msgid, msgidPlurals, count, msgctx)

For both derived stores there is a parameter msgctx which can be used to specify the context of the translation.

Extraction

Once your program is ready, you can extract the strings with one of many tools available.

For instance, you could use gettext-extractor using the following configuration:

const { GettextExtractor, RegexExtractors  } = require('@rgglez/gettext-extractor');
const pofile = require("pofile");
const fs = require("fs");

let extractor = new GettextExtractor();

extractor
    .createRegexParser([
        RegexExtractors.addCondition({
            regex: /\$_\(['"`](.*?)['"`]\)/i,
            text: 1
        })
    ])
    .parseFilesGlob('./src/**/*.@(ts|js|tsx|jsx|svelte)');

extractor
    .createRegexParser([
        RegexExtractors.addCondition({
            regex: /\$_n\(['"`](.*?)['"`]\)/i,
            text: 1,
            textPlural: 2
        })
    ])
    .parseFilesGlob('./src/**/*.@(ts|js|tsx|jsx|svelte)');    

function getPotString(headers = {}) {
    const po = new pofile();
    po.items = extractor.getPofileItems().sort((a, b) => (a.references.sort()[0] > b.references.sort()[0]) ? 1 : -1);
    po.headers = Object.assign({'Content-Type': 'text/plain; charset=UTF-8'}, headers);
    return po.toString();
}

fs.writeFileSync('./src/lib/i18n/messages.pot', getPotString());

extractor.printStats();

Just running it, for example, in the root of your project:

node gettext-config.cjs

If you already have previous po files, you can use a command like this to merge the strings:

msgmerge -U your_old_translation.po latest_strings.pot

Translation files

svelte-i18n-gettext uses standard gettext .po files, which must be manually translated into JSON using the po2json.cjs Node.js script, which is included in the bin/ directory. This script is has the following parameters:

  • Use -i, --input <input> to specify the input PO file.
  • Use -o, --output <output> to specify the output JSON file.
  • Use -v, --verbose to show verbose execution messages.

Example usage:

node po2json.cjs -i example.po -o example.json -v

Dependencies

svelte-i18n-gettext depends on the follownig node packages:

Live example

You can try this software live here.

Notes

  • Of course, you can modify the way of getting the "current language", for instance, you could get it from the user's profile store, or from a cookie, and so on. Be careful, because sometimes the language specification comes with just 2 letters (i.e. "fr") or with other local variation (i.e. "es-AR" instead of "es-MX"). You must make the necesary adjusments in these cases.
  • To edit gettext .po files you can use poEdit or some other editor.
  • I've included directories with sample .po and .json files, so, in case you're not familiar with gettext, you can have an idea of the format. Anyway, in that case I would suggest you to read the docs.
  • Why gettext?
    • First and most relevant reason: it uses the full strings in the original language as key, so I don't have to be searching for weird keys such as "page.title.hello" or "item.specification". If one translation doesn't exist, the original key string is used.
    • It's a GNU standard, tried and trusted.
  • Remember that gettext assumes that the language of the program is English by convention.
  • Any improvement or fix is welcomed.

License

Copyright (c) 2023 Rodolfo González González.

BSD-3-Clause. Read the LICENSE file.

Dependents (0)

Package Sidebar

Install

npm i svelte-i18n-gettext

Weekly Downloads

15

Version

1.0.10

License

BSD-3-Clause

Unpacked Size

19.1 kB

Total Files

15

Last publish

Collaborators

  • rgglez