5
头图
At the beginning of this article, the author is going to start a small series called modern Vue project , this article is the first internationalization i18n development

Our company’s open source tool product Bytebase is currently only available in English. Some friends in the community also asked has a Chinese version of the plan . Of course, the answer is yes. Our team is planning to release internationalization support on December 23, the next version release date. If it goes well, it will fully support the switch between Chinese and English versions.

If you have done a front-end internationalization program, your friends should know something about it. Maintaining a large number of copy translations is a headache, and freehand translation is even more personal. Based on the author's past experience, whether it is a method of extracting copywriting at a time with a copywriting tool for translation, or manually extracting copywriting to copy assets one by one. Some problems encountered in complex projects are often not as simple as translating a word or sentence.

So the author summarized some development methods to realize the internationalization of i18n in the Vue project, mainly for the Vue project. The so-called modern Vue project is the use of some useful tools, which may be something you haven’t touched before. It may be what you are using. They are some methods, tools, etc. to improve development efficiency.

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

International i18n development

Conditions met

  • VSCode
  • VSCode plugin i18n-ally
  • Vue project integration vue-i18n

Next, I will create a Vue 3 demo project through Vite to practice with you the following how to do internationalization in the Vue project

🌰 Project address:

https://github.com/xiaoluoboding/vue-i18n-practice

TL;DR

  • Initialize the Vue project
  • Configure vue-i18n in vite
  • Persisting user selection habits
  • Use i18n-ally plug-in to speed up the translation process

Initialize the Vue project

Use Vite to create a Vue project, the vue-ts template I chose

yarn create vite

✔ Project name: … vue-i18n-practice
✔ Select a framework: › vue
✔ Select a variant: › vue-ts

🔗 View commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/5fb5a8fd961448950e4523c122421771bb25fe1f

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

Configure 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/**')],
    }),
  ],
})

Use i18n as a Vue plugin:

// 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({
    legacy: false,
    locale: 'en',
    globalInjection: true,
    messages,
  })

  app.use(i18n)
}

export default install

Add a copy

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

// zh_cn.yml
common:
  home: 主页

The final display effect is as follows:

vue-i18n works

🔗 View the commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/3a16424e6885e18acfb88d7dc95d1f898bfca950

Persistent user language selection habits

After entering the site and selecting the language version, the general user hopes to enter the site again to see the language version I have selected. So we need to save the user's preferences. It is recommended to use localStorage to store user data here. Let me introduce a more useful library to combine this scenario to do user behavior persistence.

Use vueuse / Core @ library useLocalStorage implement a configuration item corresponding to the formula

Set the initial value, the next time you enter the application, localStorage will be read first, which represents the language version selected by the user

import { useLocalStorage } from '@vueuse/core'

const storage = useLocalStorage('site_locale', 'en')
const locale = storage.value

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
}

🔗 View the commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/ac3f26e098e7d884276fafa336acc953b4de7d0d

Use i18n-ally plug-in to speed up the translation process

Thanks to the i18n-ally Anthony Fu . This is a VSCode . It is not only used for translation scenarios in Vue projects. You can read the official documents.

The traditional translation process, perhaps most developers have also encountered, is to see the copy, copy and paste it into the corresponding locales file for translation, and now we can use the i18n-ally plug-in to further accelerate the translation process, maybe Just a few clicks to complete the translation of the copy.

Install VScode i18n-ally plugin

i18n-ally VSCode extension and install it

i18n-ally

Enable i18n-ally plugin

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"
}

Open the Vue component HelloWorld.vue again, you can see that some changes have taken place in the copy:

i18n ally works

This is a feature of the plug-in Inline Annotations (inline annotations) $t('common.home') written between us to English "Home". Of course, we can also map it to your preferred language by changing the configuration item "i18n-ally.sourceLanguage" the value of 061b6b03b17e7c.

Terminology of the translation process

  • language file - /locale/en.yml | /locale/zh_CN.yml
  • namespace -called path in i18n-ally, I call it "namespace"

    For example, the tree-level relationship in language files: 'common.save' , 'field.name' etc.

  • t formatting method -t method is vue-i18n , the common format is as follows:

    • Vue template interpolation- {{ $t('common.save') }}
    • Vue template component parameters- $t('common.save')
    • Vue Script- this.$t('common.save') / t('common.save')

Extract copy text to YAML language file

i18n-ally supports the extraction of the text in the code file into the language file, and supports the read and write operations of the YAML and JSON This feature has greatly improved the speed of our translation, and there is no need to manually copy and paste the text. The entire translation process does not need to open the language file. The plug-in will help extract the text and write it to the last line of the namespace.

Most of the work we have done is transformed into naming a namespace and the copywriting, and the rest is handled by the plug-in.

A rough translation process:

  1. Select copy
  2. Extract the copy to the language file, enter the namespace
  3. The alternative copy is t method
  4. Translate other language versions

translate message

🔗 View the commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/dadfdfcf307fd47868cfaa9225f5f91f937119ea

i18n Ally features

  • Quickly extract copy
  • Automatic pre-translation (can be corrected manually)
  • In-line comments within the component
  • Review system (not used yet)

These features allow us to quickly start translating copywriting, so that we can translate while developing.

Translation skills

Here are some common translation usages encountered when vue-i18n

Copy citation

Assuming that we have accumulated some word lists, then some words or phrases can be spliced by words. Linked messages is provided in vue-i18n, which provides reference to other copywriting connection grammar @:xxx , which is similar to reference variables. This mechanism is very suitable for combining words, such as translating App Name . We can define two simple words App and Name . The phrase App Name .

common:
  app: App
  name: Name
header:
  title: '@:common.app @:common.name'

Why not translate App Name directly? It’s not difficult to write. In fact, this also takes into account the problems of manual translation, typos and typos. There may be more and more mistakes. Using Linked Messages can avoid this problem, and vue -i18n also provides built-in declaration methods similar to modifiers, such as: upper , lower , capitalize , which is very helpful when translating English copywriting.

🔗 View the commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/1e9db2fb53dadac71b3d947b1c4422135c036e5c

Pass interpolation

This way is more common, similar to passing a variable, let me take the example of the official website directly:

msg while mapping the translation in the template

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

The final result is hello world

🔗 View the commit: https://github.com/xiaoluoboding/vue-i18n-practice/commit/710b8c77df617fe1916856f6109f80dbb56ee412

vue-i18n There are also some special usages such as component interpolation, singular and plural translation methods, which will not be expanded here. The official documentation is more detailed.


Finally, everyone in our team, yes, everyone, regardless of front-end and back-end, are involved in the translation of copywriting. If you are bytebase.com , or are interested in open source projects, welcome to participate in PR.

Bytebase.com is a focus in under teamwork scene database structure change and release management (Database Schema Change and Version Control for Teams is) of open source tools , mainly to solve R & D engineers and DBA (database administrator ) synergy problem when changing the database structure.

xiaoluoboding
2.1k 声望503 粉丝

I 💗 Web Dev, 💻 I'm a Senior Frontend Engineer