i18n in Vue3 hint

There is a plugin vue-cli-plugin-i18n which allows adding Vue i18n configuration super quickly into your source, but for today, 28 Jan 2021 it is not yet ported to Vue3.

However, I will show how to smoothly add i18n into your Vue3 project manually. Even when the plugin will be released, you will be able to use a manual setup anyway.

First, install 2 modules:

npm i -D vue-i18n@next
npm i -D @intlify/vue-i18n-loader@next
NOTE: today these commands installed next versions: @intlify/vue-i18n-loader@2.0.0-beta.3 and vue-i18n@9.0.0-rc.4 . In future this beta and rc will become current versions so you will need to remove @next from install commands

Now, in main.js for your project, connect i18n module:

import { createI18n } from 'vue-i18n';

const i18n = createI18n({
  locale: 'es', // you can define your language basing on your settings, 
                       //e.g. read from domain (es.example.com -> window.location.hostname.split('.')[0]) 
  legacy: false,
});

app.use(....).use(i18n).mount('#app');

Now, in root dir (same level with package.json), create a file vue.config.js, and add the next code there:

module.exports = {
  chainWebpack: config => {
    config.module
      .rule('i18n')
      .resourceQuery(/blockType=i18n/)
      .type('javascript/auto')
      .use('i18n')
      .loader('@intlify/vue-i18n-loader')
      .end()
  }
}

Now, in your component (.vue) file add:

import { useI18n } from 'vue-i18n';

export default {
    setup() {
      const { t } = useI18n();
      return {
        t,
      }
   }
}

We are almost there. From this moment, in Template section of the component you can use t-strings like this:

<template>
   <div class="home">
        <p>
          {{ t('Hello friends') }}          
        </p>
  </div>
</template>

And here is the thing:

<i18n>
{
  "es": {
    "hello": "Hola amigas"
  }
}
</i18n>

Yes, you can keep all strings inside of files where they are used.

After-release CLI method

In your Vue project run

vue add i18n
NOTE: You need nodejs version later or equal to 12, otherwise you will receive "error [email protected]: The engine "node" is incompatible with this module. Expected version ">= 12". Got "10.23.0"

To install nodejs 12 on Ubuntu use:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - && sudo apt-get install -y nodejs

If you have no vue3 project, you can create it with

vue create my-vue-app

When it asks, don't forget to tick y for Locale messages in Single File components with