sveltesvelte-3snowpack

Calling i18n.js file on app's entry-point | svelte-i18n


I am trying to internationalize my Svelte app.

I am using Svelte with Snowpack. And svelte-i18n. I follow their tutorial on GitHub.

In the tutorial, they say :

"Note: Make sure to call your i18n.js file on your app's entry-point. If you're using Sapper, remember to also call init() on your server-side code (server.js)."

I don't know how to do it? Can anyone please help me?

Any help is very much appreciated.


Solution

  • The entry point is the file where you initialize your app. If you are using the default Svelte template, the entry point is src/main.js. You can place the i18n code there.

    import App from './App.svelte';
    // copied from https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting%20Started.md#4-initializing
    import { register, init, getLocaleFromNavigator } from 'svelte-i18n';
    
    register('en', () => import('./en.json'));
    register('en-US', () => import('./en-US.json'));
    register('pt', () => import('./pt.json'));
    // en, en-US and pt are not available yet
    
    init({
        fallbackLocale: 'en',
        initialLocale: getLocaleFromNavigator(),
    });
    // starts loading 'en-US' and 'en'
    
    // now render your app
    const app = new App({
        target: document.body,
        props: {
            name: 'world'
        }
    });
    
    export default app;
    

    The package also provides a template for doing this in Sapper.