This is a Svelte component based on derived stores which implements gettext based translation (i18n) of strings.
npm install svelte-i18n-gettext
import { _, _n } from 'svelte-i18n-gettext/src/index.svelte';
import { parsedTranslations, lang } from 'svelte-i18n-gettext/src/store.js';
lang
(or a local alias) store to specify the language to use:$lang = 'es-MX';
$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>
$_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.
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:
-i, --input <input>
to specify the input PO file.-o, --output <output>
to specify the output JSON file.-v, --verbose
to show verbose execution messages.Example usage:
node po2json.cjs -i example.po -o example.json -v
svelte-i18n-gettext depends on the follownig node packages:
You can try this software live here.
Copyright (c) 2023 Rodolfo González González.
BSD-3-Clause. Read the LICENSE file.