This is a small project demonstrating a typesafe-i18n
integration with Svelte.
LIVE-DEMO: https://typesafe-i18n-demo-svelte.vercel.app
This is a clone from the Vite Svelte Typescript starter template
Start Vite in development mode:
npm run dev
Navigate to http://localhost:3000. You should see the example app running.
Initialize typesafe-i18n
by running
npx typesafe-i18n --setup-auto
You could configure your development script to run the generator in parallel to vite
by using npm-run-all
.
{
"scripts": {
"dev": "npm-run-all --parallel vite typesafe-i18n",
"vite": "vite",
"typesafe-i18n": "typesafe-i18n",
}
}
The generator will create some custom Svelte stores inside i18n-svelte.ts
that you can use inside your components.
Then inside your root-component, you need to load your locales and call setLocale
in order to setup all stores.
<script lang="ts">
import { setLocale } from './i18n/i18n-svelte'
// TODO: load locales (https://github.com/ivanhofer/typesafe-i18n#loading-locales)
setLocale()
</script>
<!-- HTML markup -->
That's it. You can then start using typesafe-i18n
inside your Svelte application.
<script lang="ts">
import LL from './i18n/i18n-svelte'
</script>
<h1>{$LL.HELLO({ name: 'Svelte' })}</h1> <!-- "Hello Svelte!" -->
When running the generator, the file i18n-svelte.ts
will export following functions and readable stores:
Call it inside your root Svelte component in order to setup the stores:
<script>
import { initI18n } from './i18n/i18n-svelte'
initI18n('en')
</script>
The default export of the generated file will be the store you can use to translate your app. You can use it with subscriptions ($LL
) or as a regular JavaScript object (LL
).
<script>
import LL from './i18n/i18n-svelte'
const showMessage = () => {
alert(LL.SOME_MESSAGE())
}
</script>
{$LL.HELLO({ name: 'world' })}
<button on:click={showMessage}>click me</button>
This Svelte store will contain the current selected locale.
<script>
import { locale } from './i18n/i18n-svelte'
</script>
<div>
your language is: {$locale}
</div>
If you want to change the locale, you need to call setLocale
with the locale as an argument.
<script>
import { setLocale } from './i18n/i18n-svelte'
</script>
<div id="language-picker">
Choose language:
<button on:click={() => setLocale('en')}>
english
</button>
<button on:click={() => setLocale('de')}>
deutsch
</button>
<button on:click={() => setLocale('it')}>
italiano
</button>
</div>
See here
For your Sapper projects, you should call the initI18n
function inside preload
in your root routes/_layout.svelte
file:
<script context="module">
import { initI18n } from '../i18n/i18n-svelte'
export async function preload(page, session) {
// detect locale of user (see https://github.com/ivanhofer/typesafe-i18n#locale-detection)
const locale = 'en'
await initI18n(locale)
}
</script>
For more information about the stores you can use, see the Svelte section.
For more information about typesafe-i18n
, take a look at the main repository.