At the beginning of this article, I’m going to start a short series called Modern Vue Engineering. This is the first of a series called “International I18N Development.”

Bytebase, an open source tool of our company, is only available in English at present. Some friends in the community also asked whether there is a Chinese version of the plan, the answer is of course yes. Our team is planning to release internationalization support on December 23, the next release date. If successful, we will fully support switching between Chinese and English versions.

If you have done the front-end internationalization plan, you should know that maintaining a large number of copywriting translation is very troublesome, and unarmed translation is more physical work. According to the author’s previous experience, it is not only the method of extracting documents for translation with the document extraction tool at a time, but also the method of extracting documents to document assets one by one manually. Some of the problems encountered in complex projects are not as simple as translating a word or a sentence.

Therefore, the author summarizes some development methods to achieve international I18N in Vue project, mainly for Vue project, the so-called modern Vue project is to use some good tools, may be you have not touched before, may be you are using, they are some methods to improve the efficiency of development, tools and so on.

The main tool introduced in this issue is the VSCode plug-in i18n-ally

Internationalize i18N development

Satisfied condition

  • VSCode
  • VSCode plug-in i18n – ally
  • Vue engineering integration Vue – I18N

Next, I will create a Vue 3 demo project using Vite to practice the following: how to do internationalization in Vue project

🌰 Project Address:

Github.com/xiaoluobodi…

TL; DR

  • Initialize the Vue project
  • Configure vuE-I18N in Vite
  • Persist user selection habits
  • Use the I18N-ALLY plug-in to speed up the translation process

Initialize the Vue project

Using Vite to create a Vue project, I chose the VUE-TS template

Yarn create vite stocking Project Name:... Vue-i18n-practice ➤ ➤ Vue - i18N-practice ➤ ➤ ➤ Select a framework from a variantCopy the code

🔗 View Commit: github.com/xiaoluobodi…

Configure vuE-I18N in Vite

Three libraries need to be installed:

  • vue-i18n@next
  • @types/node
  • @intlify/vite-plugin-vue-i18n

PS. In the Vue 3 project we need to install the next version of VUE-I18N

yarn add vue-i18n@next -S && yarn add @types/node @intlify/vite-plugin-vue-i18n -D
Copy the code

Configuration vite. Config. Ts

Specify the locales file path as SRC /locales

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import VueI18n from '@intlify/vite-plugin-vue-i18n'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // https://github.com/intlify/vite-plugin-vue-i18n
    VueI18n({
      // define the locales files directory
      include: [resolve(__dirname, 'src/locales/**')]}),],})Copy the code

Using i18N as a Vue plug-in:

// plugins/i18n.ts
import { App } from 'vue'
import { createI18n } from 'vue-i18n'

const localPathPrefix = '.. /locales/'

// import i18n resources
// https://vitejs.dev/guide/features.html#glob-import
const messages = Object.fromEntries(
  Object.entries(import.meta.globEager('.. /locales/*.y(a)? ml')).map(
    ([key, value]) = > {
      const yaml = key.endsWith('.yaml')
      return [key.slice(localPathPrefix.length, yaml ? -5 : -4), value.default]
    }
  )
)

const install = (app: App) = > {
  const i18n = createI18n({
    legacyfalse.locale'en'.globalInjectiontrue,
    messages,
  })

  app.use(i18n)
}

export default install
Copy the code

Add a copy

<template>
 <h1>{{ $t('common.home') }}</h1>
</template>
Copy the code
// en.yml
common:
  home: Home

// zh_cn.yml
common:
  home: The home page
Copy the code

The final display is as follows:

vue-i18n works

🔗 View Commit: github.com/xiaoluobodi…

Persist user language selection habits

The average user will enter the site after selecting the language version, want to re-enter the site or see the language version I selected. So we need to save the user’s preferences. It is recommended to use localStorage to store user data. Let me introduce a library that is better used to do user behavior persistence combined with this scenario.

Implement a corresponding configuration item using useLocalStorage in the @vueuse/core library

Set the initial value. The value in localStorage is read preferentially when you enter the application next time. It represents the selected language version

import { useLocalStorage } from '@vueuse/core'

const storage = useLocalStorage('site_locale'.'en')
const locale = storage.value
Copy the code

Follow the button to switch the language version and set it to localStorage

const setLang = (lang: string) = > {
  const storage = useLocalStorage('site_locale'.' ')
  storage.value = lang
}
Copy the code

🔗 View Commit: github.com/xiaoluobodi…

Use the I18N-ALLY plug-in to speed up the translation process

I18n-ally is a universal, one-stop translation plugin based on VSCode, not only for Vue project translation scenarios, you can read the official documentation.

The traditional translation process, which most developers have probably encountered, is to see a copy and paste it into a locales file for translation. Now with the help of the i18N-Ally plugin, we can speed up the translation process even further, probably with a few clicks.

Install the VScode i18N-ally plugin

Search for i18n-ally installation in the VSCode extension

i18n-ally

To enable thei18n-allyThe plug-in

It is recommended to use the.vscode configuration item in the project

.vscode/settings.json

// .vscode/settings.json
{
  "i18n-ally.localesPaths": [
    "src/locales"]."i18n-ally.enabledParsers": [
    "yaml"]."i18n-ally.sourceLanguage""en"."i18n-ally.displayLanguage""zh-cn"."i18n-ally.keystyle""nested"
}
Copy the code

Open the Vue component helloWorld.vue again and you can see some changes to the copy:

i18n ally works

Annotations, Inline Annotations, map code like $T (‘common.home’) written between us to the English “home”, or to your favorite language, Set by changing the value of “i18n-ally. SourceLanguage “in the configuration item.

Terminology of the translation process

  • “Language file” – / locale/en. Yml | / locale/zh_CN. Yml

  • “Namespace” – called a path in i18N-ally, I call it a “namespace”

    Examples are tree hierarchies in language files: ‘common.save’, ‘field.name’, etc

  • T Formatting method -t is a copy formatting and translation method provided by VUE-i18N. The commonly used format is as follows:

    • Vue template interpolation –{{ $t('common.save') }}
    • Vue template component parameters –$t('common.save')
    • – in the Vue Scriptthis.$t('common.save') / t('common.save')

Extract the copy to the YAML language file

I18n-ally supports extracting text from code files into language files and reading and writing YAML and JSON files. This feature greatly improves the speed of our translation, no longer need to manually copy and paste the text, the whole translation process we can not open the language file, plug-in will help to extract the text to the corresponding namespace under the last line.

Most of the work we did was converted to naming a namespace correspondence to the copy, leaving the rest to the plug-in.

A general translation process:

  1. Select copy
  2. Extract copy to language file, inputThe namespace
  3. Replace the copy withT method
  4. Translation in other languages

translate message

🔗 View Commit: github.com/xiaoluobodi…

I18n Ally features

  • Quick copy extraction
  • Automatic pre-translation (manual correction)
  • Component internal line comments
  • Review System (not currently in use)

These features allow us to quickly get started with translation copywriting and achieve the status of translating while developing.

Translation skills

Here is a brief introduction to some of the common translation usages encountered when using vue-i18n.

Copy reference

Assuming we have accumulated a list of words, there are words or phrases that can be pieced together. Vue-i18n provides Linked messages, which provides the syntax @: XXX for referencing other copytexts, similar to referencing variables. This mechanism is very suitable for combining words, such as translating App Name. We can define two simple words App and Name. Make a phrase App Name.

common:
  app: App
  name: Name
header:
  title: '@:common.app @:common.name'
Copy the code

Why not translate App Name directly? It is not difficult to write. In fact, it also takes into account the problems of clerical errors and wrong words in human translation. Vue-i18n also provides built-in modifiers such as upper, lower, capitalize that are useful when translating English text.

🔗 View Commit: github.com/xiaoluobodi…

Pass the interpolation

This method is more common, like passing a variable, I directly take the official website example:

Pass a MSG while mapping the translation in the template

<p>{{ $t('common.hello', { msg: 'hello' }) }}</p>
Copy the code
common:
  hello: '{msg} world'
Copy the code

The final display is Hello World

🔗 View Commit: github.com/xiaoluobodi…

Vue-i18n also has some special uses such as component interpolation, singular plural and other special translation methods, which will not be expanded here. Official documents are more detailed.


Finally, everyone on our team, yes, everyone, both front and back, is involved in translating copywriting. If you are interested in bytebase.com, or open source projects, you are welcome to participate in PR.

Bytebase.com is an open source tool that focuses on Database Schema Change and Version Control for Teams, It mainly solves the coordination problem between r&d engineers and DBA (database administrator) when changing the database structure.