DEV Community

Fazail Alam
Fazail Alam

Posted on • Originally published at codef.site on

Add support for i18n in your nuxt3 application

"nuxt3 i18n support"

The time i am writing this article, latest nuxt version is -> v3.0.0-rc.8

If you have already a nuxt3 project, then skip this section.

Installation

 npx nuxi init nuxt-i18n
Enter fullscreen mode Exit fullscreen mode

Install dependencies with npm i.

Adding @intlify/nuxt3

Run below command to install @intlify/nuxt3 as dev dependency, then add @intlify/nuxt3 in modules section of nuxt.config.ts.

 npm install --save-dev @intlify/nuxt3
Enter fullscreen mode Exit fullscreen mode
modules: ["@intlify/nuxt3"];
Enter fullscreen mode Exit fullscreen mode

Now add the options for @intlify/nuxt3 below of modules, you can also provide vueI18n options as this package is built on top of vueI18n.

 intlify: {
        localeDir: 'locales', // this the path for languages json files
        vueI18n: {
            // you can add vueI18n option here
        }
    }
Enter fullscreen mode Exit fullscreen mode

Create languages files

Create new directory inside your project's root folder named locales, Note: this name should have to be same as provided in intlify:'locales'. Since this is the directory that this package will look for json files.

Inside those two json files add the languages key and value you want to change.

//en.json
{
    "hello": "Hello {name}!",
    "language": "Language"
}
Enter fullscreen mode Exit fullscreen mode
//fr.json
{
    "hello": "Bonjour, {name}!",
    "language": "Langue"
}
Enter fullscreen mode Exit fullscreen mode

Ready to Test

There is global function that is provided by this package named $t(<key>,{<param>}).

<template>
    <div>
        <h1>{{ $t("hello", { name: "Fazail" }) }}</h1>
        <form>
            <label for="locale-select">{{ $t("language") }} </label>
            <select id="locale-select" v-model="$i18n.locale">
                <option value="en">en</option>
                <option value="fr">fr</option>
            </select>
        </form>
    </div>
</template>
Enter fullscreen mode Exit fullscreen mode

In the above code "hello" is the key, and name is the parameter that will be replaced by the same keyword used inside "{keyword}" Check here more details. Notice we have binded the global $i18n.locale variable with v-model. So whenever we select a new value language will change. Note: select's option value should be same name of the corresponding language file.

Top comments (0)