How to set up i18n in Vue

Internationalization (i18n) is a crucial aspect of building multilingual Vue 3 applications. In this guide, we'll walk you through the process of setting up i18n using the vue-i18n library and utilizing JSON files to translate your Vue apps effectively.

Internationalization (i18n) is a crucial aspect of building multilingual Vue 3 applications. In this guide, we'll walk you through the process of setting up i18n using the vue-i18n library and utilizing JSON files to translate your Vue apps effectively.

Installation

First, let's install the vue-i18n library using your package manager of choice. We'll use pnpm in this example:

pnpm add vue-i18n@9

Creating a New Localization Project

To get started with i18n, you need to create a localization project. You can use tools like verbcode to manage your translations. Follow these steps:

  1. Open up the verbcode app and create a new localization project.
  2. Select the languages you want to support and add your first translation file.
showing the screen to create a new localization project in verbcode
  1. Save the project to your preferred location, typically within your project's src/locales directory.

Setting up i18n

Now, let's configure vue-i18n by creating a separate file to reference the translation function outside of the Vue setup context. verbcode will automatically generate a file named locales.js for you. It's a default export.

// src/utils/i18n.ts
import { createI18n } from "vue-i18n";
import messages from '@/locales/locales.js';

export const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages
});

Next, import and use this configuration in your main.ts file:

// src/main.ts
import App from "./App.vue";
import { i18n } from "@/utils/i18n";

const app = createApp(App);
app.use(i18n);
app.mount("#app");

Now, you're all set to create a multilingual Vue 3 application with ease using i18n!

Using i18n

With the setup complete, you can now use i18n throughout your Vue project in various ways:

In templates

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

In script blocks

<script setup lang="ts">
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const message = t('hello')
</script>

In typescript files

import { i18n } from '@/utils/i18n'

const message = i18n.global.t('hello')

For more details on using vue-i18n, check out the official documentation