目标
对现有vue前端项目i18n-demo进行国际化改造,替项目中硬编码中文为代号(code)。该项目使用vue-i18n插件实现国际化功能。
工具
vue-i18n
vscode
示例
1、引入vue-i18n及语言配置
main.js
import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import './style.css';
import App from './App.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh',
fallbackLocale: 'en',
messages: {
en: {
message: {
hello: 'hello world',
},
},
zh: {
message: {
hello: '你好,世界',
},
},
},
});
const app = createApp(App);
app.use(i18n);
app.mount('#app');
vue文件,HelloWorld.vue
<script setup>
const msg = '你好,世界';
</script>
<template>
<div class="card">
<p>你好,世界</p>
<p>{{ msg }}</p>
<p>{{ true ? '你好,世界' : '' }}</p>
</div>
</template>
将 HelloWorld.vue 改造为
<script setup>
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const msg = t(/* 你好,世界 */ 'message.hello');
</script>
<template>
<div class="card">
<p>{{ $t(/* 你好,世界 */ 'message.hello') }}</p>
<p>{{ msg }}</p>
<p>{{ true ? $t(/* 你好,世界 */ 'message.hello') : '' }}</p>
</div>
</template>
2. 借助vscode代码片段
当前项目存在大量硬编码中文时,一个个手动替换需要大量时间,且容易出错,借助vscode snippet可辅助我们轻易改造。
1、打开vscode -> 文件 -> 首选项 -> 配置用户代码片段 -> 新建"i18n-demo"文件夹的代码片段文件...,会生成该项目的局部代码片段配置文件i18n-demo.json.code-snippets,向配置文件中添加下列内容:
{
// Place your i18n-demo 工作区 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
"message.hello.script": {
"scope": "javascript,typescript",
"prefix": "'你好,世界'",
"body": [
"t(/* 你好,世界 */ 'message.hello')",
],
"description": "你好,世界"
},
"message.hello.script2": {
"scope": "javascript,typescript",
"prefix": "'你好,世界'",
"body": [
"\\$t(/* 你好,世界 */ 'message.hello')",
],
"description": "你好,世界"
},
"message.hello.template": {
"scope": "html",
"prefix": "你好,世界",
"body": [
"{{ \\$t(/* 你好,世界 */ 'message.hello') }}",
],
"description": "你好,世界"
}
}
2、配置vscode快捷方式“触发建议”,如“Alt+/”。将光标定位到需要替换的中文末尾,按下Alt+/,触发建议,选择合适的建议回车确认。
其中,"message.hello.script"用来匹配<script></script>中的javascript/typescript代码:
"message.hello.script2"用来匹配<template></template>中的javascript/typescript代码:
"message.hello.template"用来匹配<template></template>中的html代码:
3. 实战建议
对真实项目改造前,先整理出所有的中文对应代码清单,和多语言文件。根据中文代码清单,书写相应脚本自动生成projectName.json.code-snippets配置文件。注意代码片段scope的选择,除上述的javascript、typescript、html,还有javascriptreact、typescriptreact等针对JSX、TSX文件。
还要注意的是,文本是由单引号包裹,或者双引号包裹,其对应的代码片段也是不同的,需要考虑多种情况。
4. 思考
文本中包含变量时,应该如何配置代码片段?