目录
前言
之前项目里做国际化处理都是在初始化的时候就给集成了,新增了哪些文字内容,将翻译内容直接粘贴到对应的语言文件里就好了, 也没感觉有多大的工作量, 但是最近一个比较大的项目需要添加国际化的功能,每个页面都得单独的去处理,再加上翻译文件,一整个难受啊...
都是些复制粘贴费眼睛的辛苦活, 页面只能挨个的去改了,那就在翻译文件上偷点懒吧。
一、i18n的常规使用
1. 安装依赖
npm install vue-i18n -S
2. 创建文件
// zh.js
export const zh = {
店铺: '店铺',
}
// en.js
export const en = {
店铺: 'Stores',
}
// index.js
import locale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { zh } from './zh'
import { en } from './en'
Vue.use(VueI18n)
const messages = {
zh: { ...zhLocale, ...zh },
en: { ...enLocale, ...en },
}
const i18n = new VueI18n({
locale: localStorage.getItem('lang') || 'zh', // 初始化配置语言
messages: messages,
silentTranslationWarn: true,
})
locale.i18n((key, value) => i18n.t(key, value))
export default i18n
// 在 main.ts 中添加如下代码:
import i18n from './language'
const vue = new Vue({
el: '#app',
router,
store,
i18n,
render: (h) => h(App),
})
二、语言包翻译的偷懒做法
一般需要翻译的内容都是找专门的翻译提供的,到开发手上都是一个表格,如果一个一个复制粘贴到对应语言包文件,累人又耗时, 我们可以直接将excel转成json文件,再处理一下json文件即可。
1. 安装依赖
npm install xlsx-to-json
2. 创建文件
将excel文件放在language下,在创建一个i18n.json文件(语言包文件可以删掉了):
i18n.xlsx:
// 使用xlsx2json插件将i18n.xlsx解析成json文件,保存在i18n.json文件里
const xlsx2json = require('xlsx-to-json')
const path = require('path')
xlsx2json(
{
input: path.join(__dirname, './i18n.xlsx'),
output: path.join(__dirname, './i18n.json'),
},
function (err) {
if (err) console.error(err)
},
)
在package.json文件的scripts中加上如下命令, 然后执行 npm run i18n,即可生成解析好的json文件。
"scripts": {
"i18n": "node ./src/language/excel2json.js"
},
解析后的文件:
最后修改index.js文件:
import locale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import idLocale from 'element-ui/lib/locale/lang/id'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import i18nJson from './i18n.json'
Vue.use(VueI18n)
// 动态获取 message 信息
function getMessage() {
const messages = { zh: { ...zhLocale }, en: { ...enLocale }, id: { ...idLocale } }
i18nJson.forEach((columns) => {
const name = columns.Chinese
messages.zh[name] = columns.Chinese
messages.en[name] = columns.English
messages.id[name] = columns.Indonesia
})
return messages
}
const i18n = new VueI18n({
locale: localStorage.getItem('lang') || 'zh', // 初始化配置语言
messages: getMessage(),
silentTranslationWarn: true,
})
locale.i18n((key, value) => i18n.t(key, value))
export default i18n
总结
由于时间原因,能找到的偷懒办法就只有这么点了,后面再研究吧。