Localization with Vue 3 and i18n
i18n package
Adding different locales and translations for your website using VueJs could be a challenge but using the i18n package is a breeze, to start install it:
npm install vue-i18n@11A few settings to do
// app.js
import i18n from '@/plugins/i18n'
app.use(i18n)
// use it in a component
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
// or
const { t, locale } = useI18n()and you are about done, the package is ready to use.
The package is immensely useful no doubt about that, but there a few strange things about it…
Just the other day I had a peculiar error that popped up:
Error 23
wait what? that’s the error message nothing else…
It turns out that in production, vue-i18n strips the human-readable message and the error message becomes the bare numeric code from @intlify/core-base. Code 23 = "cannot support locale type",
After a few hours of digging I learned that the error is actually caused by the fact that I was passing undefined to the package via it’s property locale
Naturally I’ve fixed the error by adding checks for the specific cases and set a default locale value so it will be always set properly regardless.
const { locale } = useI18n()
locale.value = lang ?? 'en'It’s a great package, immensely helpful but the error handling should be a bit better IMO.
Conclusion
Every now and then there is such cases that can wow you, but it the end of the day they could be very helpful learning new things.