A Message Format 2 formatter component for SvelteKit with @sveltekit-i18n/base
npm install sveltekit-mf2A localization library for SvelteKit based on sveltekit-i18n/base and MessageFormat2.
``bash`
npm install sveltekit-mf2
`bash`
npm install @sveltekit-i18n/base messageformat
Create the translations.ts file in you lib folder.
`ts
import i18n from "@sveltekit-i18n/base";
const config = {
// Add your languages in the loaderfunction eaither from JSON files or directly as JSON
loaders: [
{
locale: "en",
key: "common",
loader: async () => (await import("./en/common.json")).default
},
{
locale: "es",
key: "common",
loader: async () => (await import("./es/common.json")).default
}
],
parser: {
parse(value: string, [props]: Record
return { value, props, locale };
}
}
};
export const { setLocale, t, locale, locales, loading, loadTranslations } = new i18n(config);
`
en/common.json
`json`
{
"test": "Hello {#bold}{$world}!{/bold}",
"bye": "Bye"
}
es/common.json
`json`
{
"test": "Hola {#bold}{$world}!{/bold}",
"bye": "adios"
}
#### Make sure to not change the parser!
Inside of your +layout.svelte use the by importing t and sorounding {@render children} with the provider.
`ts
{@render children()}
`
Create a layout.ts file in your routes folder.
`ts
import { loadTranslations } from "$lib/translations";
const initLocale = "en";
export const load = async ({ url }) => {
await loadTranslations(initLocale, url.pathname);
};
`
The component takes in an id which uses the loader key and the key value in the JSON oject to reference the correct line. Props are the variables passed to the Messageformat string.
`ts
References
Message Format 2
svleltekit-i18n/base
$3
####
Props:
t - The t function from the i18n object$3
#####
Props:
-
id: string - Translation key (e.g., "common.greeting")
- values: Record