Multilang with i18n in Vue

Multilang was the most important part of my applications. Always. When I start coding some applications I always start by adding multilang to my app. Today I will show you how to add the i18n library to your Vue app. It’s a simple library that allows you to create separate files for all languages you will support.

Multilang? But why?

Before we will jump to the code I want to answer a question from the heading. Why I always taking care of multilang? Starting a new application and trying to validate it I always looking for clients in my country. I’m from Poland. A big part of polish people is weak from English. Unfortunately. I want to make sure that most of my perfect clients will understand each of the texts in my app. On the other hand, I don’t want to close my app only for Polish people. I want to go with it to as many clients as possible. That’s why I always start from add i18n to my project.

Multilang library

I always use the i18n library for my Vue projects. It’s easy to use and powerful library. You can find more information about it here.

Let’s jump to code!

First I need to create a new empty Vue project. I will do it by typing below command in terminal.

vue create app

This command will prompt some questions about my new project. All of it will be about configurations and some plugins appended to the project since the beginning. I will create a separate post about it. For now, you need to know that I’m choosing Vue 3 and TypeScript for my project. There is two options now.

Option 1: Easy one

This option is really easy. You have to use vue-cli for installing i18n plugin. You can do it with only one command in terminal. Go to the root directory of your project and type

vue add i18n

And now vue-cli will do everything for you. Really. You don’t need anything more. But…

Well, this method doesn’t work for Vue 3 yet. If you are using Vue 3 you have to choose option 2.

Option 2: A little harder one

The second method is a little bit harder because you have to set up everything on your own. So, first of all, you have to install one package for your project. If you are using yarn, the command should look like the one below.

yarn add vue-i18n@next

If you don’t like yarn and you are using npm the command will be like that.

npm install vue-i18n@next

When you install our multilang library then you have to configure it. And now I will show you how to do that.

Creating i18n configuration

First file I will create is i18n.ts. To be honest, that file was created by vue-cli in Vue 2. I just copied it to a new project.

import { createI18n, LocaleMessages, VueMessageType } from 'vue-i18n';

function loadLocaleMessages(): LocaleMessages<VueMessageType> {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages: LocaleMessages<VueMessageType> = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default createI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
});

The first function is used to load all files from the locales directory. This is a new directory where I will add translations. Each translation should be a JSON file with a name from the letters of the language. For example, en.json is a file with English translations. In the lasts lines, you can see that this file returning a new instance of i18n. To create this instance I have to pass 3 arguments. First is the current using lang. Then you see the key falbackLocale it says what should be used when the locale file can not be found. The last key representing all translation files found in the locales directory.

Translations files

Translation files are a normal JSON files.

{
  "message": "hello i18n !!",
  "page": {
  	"text": "translation"
  }
}

You can create any structure you want. It will be resolved later in views.

Including i18n in main.ts

Before I will be able to use these translations in views, I have to include the prepared config in the main.ts file. This file contains code that creates an instance of Vue. So I have to import i18n file and use it in createApp chain.

import { createApp } from 'vue';
import i18n from './i18n';
import App from './App.vue';
import router from './router';
import store from './store';

createApp(App).use(i18n).use(store)
  .use(router)
  .mount('#app');

And that’s all. Now I can use all translations declared in en.json in every Vue file in the entire project.

How to use multilang?

Well it’s pretty easy to use translations when you have access to it from. I created some example view to show you how to do that.

<template>
  <p>{{ $t('hello') }} {{ $t('page.text') }}</p>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'HelloI18n',
});
</script>

Multilang is easy

And this is the end. Now you know how to add the i18n library to your Vue project. It’s really easy. In the next post, I will show you how to create some language switch! Hope you will found this article helpful. If you have any questions just ask them in the comment section. I will answer all comments.

See you soon!