This project shows how to leverage a SvelteKit application in several languages, without using any additional library.
This is demonstrated with a simple todo app, but it could be any application. The routes are not changed.
The translation-related files are:
LanguageSelect.svelte
- the component that allows the user to select a language (saved in a cookie) that may differ from their browser defaulti18n
and all its contents - the main logictranslations
folder - contains one JSON file per supported languagesrc/hooks.server.ts
- loads the language from the accent-language header or the cookiesrc/routes/+layout.server.ts
- loads the language from the hooksrc/routes/+layout.svelte
- sets the language as a contextThe main function is the t
function exported from i18n/translate.ts
. In a Svelte component, we can use it as follows.
{t('Todos.Title')}
This function is fully typed and therefore offers a convenient autocompletion for the available keys.
Translations with parameters are also possible:
// en.json
{
"Summary": "There are {{ count }} todos in total."
}
<!-- Todos.svelte -->
{t('Summary', { count: todos.length })}