sveltekit-i18n
sveltekit-i18n
is a tiny library with no external dependencies, built for Svelte and SvelteKit. It glues @sveltekit-i18n/base and @sveltekit-i18n/parser-default together to provide you the most straightforward sveltekit-i18n
solution.
Note this README is related to sveltekit-i18n@2.x
. If you are looking for version 1.x
you can find it here.
Key features
Usage
Setup translations.js
in your lib folder...
import i18n from 'sveltekit-i18n';
/** @type {import('sveltekit-i18n').Config} */
const config = ({
loaders: [
{
locale: 'en',
key: 'common',
loader: async () => (
await import('./en/common.json')
).default,
},
{
locale: 'en',
key: 'home',
routes: ['/'], // you can use regexes as well!
loader: async () => (
await import('./en/home.json')
).default,
},
{
locale: 'en',
key: 'about',
routes: ['/about'],
loader: async () => (
await import('./en/about.json')
).default,
},
{
locale: 'cs',
key: 'common',
loader: async () => (
await import('./cs/common.json')
).default,
},
{
locale: 'cs',
key: 'home',
routes: ['/'],
loader: async () => (
await import('./cs/home.json')
).default,
},
{
locale: 'cs',
key: 'about',
routes: ['/about'],
loader: async () => (
await import('./cs/about.json')
).default,
},
],
});
export const { t, locale, locales, loading, loadTranslations } = new i18n(config);
...load your translations in __layout.svelte
...
<script context="module">
import { locale, loadTranslations } from '$lib/translations';
export const load = async ({ url }) => {
const { pathname } = url;
const defaultLocale = 'en'; // get from cookie, user session, ...
const initLocale = locale.get() || defaultLocale; // set default if no locale already set
await loadTranslations(initLocale, pathname); // keep this just before the `return`
return {};
}
</script>
...and include your translations within pages and components.
<script>
import { t } from '$lib/translations';
const pageName = 'This page is Home page!';
</script>
<div>
<!-- you can use `placeholders` and `modifiers` in your definitions (see docs) -->
<h2>{$t('common.page', { pageName })}</h2>
<p>{$t('home.content')}</p>
</div>