Often a multi-language application can be needed to be able to speak to a wider audience of people.
It can always be useful to localize your application according to who you want to talk to, while still being able to read to anyone with more classical English.
We can use the install command:
npm install @nuxtjs/i18n
Then in nuxt.config.js
we need to add:
export default {
// ...
modules: [
'@nuxtjs/i18n',
],
i18n: {
/* module options */
},
// ...
}
And in tsconfig.json
(in the case of Typescript) we need to add:
{
"compilerOptions": {
"types": [
"@nuxt/types",
"@nuxtjs/i18n",
]
}
}
Lazy translation
It may happen that for some translations it is necessary to refer to an external source, perhaps not properly under our control. It is in these cases that the “lazy” mode of the translate system comes in handy.
To do this we must add the ad hoc configuration to our nuxt.config.js, also calling up a js that we will define shortly.
export default {
// ...
i18n: {
/* module options */
locales: [
{
code: 'en',
file: 'i18n.js' // External messages loading.
},
],
lazy: true,
defaultLocale: 'en',
langDir: '~/',
},
// ...
}
Inside our javascript we define our default label fetch function.
// i18n.js
export default async (context, locale) => {
return await fetch(`https://www.example.it/lang/${locale}.json`)
.then(response => response.json())
.then(data => data);
}
That’s all.
Try it at home.