Add support for i18n in your nuxt3 application

Add support for i18n in your nuxt3 application

Easily add support for i18n in your nuxt3 application using @intlify/nuxt3.

Fazail Alam
Frontend dev · Sat Aug 13 2022

Nuxt3 is in release candidate mode.

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

terminal
 npx nuxi init nuxt-i18n

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.

terminal
 npm install --save-dev @intlify/nuxt3
nuxt.config.ts
modules: ["@intlify/nuxt3"];

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.

nuxt.config.ts
intlify: {
	localeDir: 'locales', // this the path for languages json files
	vueI18n: {
		// you can add vueI18n option here
	}
}

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"
}
fr.json
{
    "hello": "Bonjour, {name}!",
    "language": "Langue"
}

Ready to Test

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

app.vue
<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>

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.

Want frameworks news and updates?

Sign up for our newsletter to stay up to date.

Share on: