實現思路
- i18next-scanner 自動掃描代碼中的中文
- 中文作為多語言的key,通過crc32轉為語音包的key
i18next-scanner 使用
package.json寫入script自動運行腳本 npm run scan
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "npm run scan && node build/build.js",
"scan": "i18next-scanner --config build/i18next-scanner.config.js"
},
配置
const fs = require('fs');
const { crc32 } = require('crc');
module.exports = {
input: [
'src/**/*.{js,jsx,vue}',
// Use ! to filter out files or directories
'!src/**/*.spec.{js,jsx,vue}',
'!src/i18n/**',
'!**/node_modules/**',
],
output: './', //輸出目錄
options: {
debug: true,
func: false,
trans: false,
lngs: ['cn', 'en'],
defaultLng: 'cn',
resource: {
loadPath: './src/i18n/{{lng}}/{{ns}}.json', //輸入路徑
savePath: './src/i18n/{{lng}}/{{ns}}.json', //輸出路徑
jsonIndent: 2,
lineEnding: '\n'
},
removeUnusedKeys: true,
nsSeparator: false, // namespace separator
keySeparator: false, // key separator
interpolation: {
prefix: '{{',
suffix: '}}'
}
},
transform: function customTransform(file, enc, done) {//自己通過該函數來加工key或value
"use strict";
const parser = this.parser;
const content = fs.readFileSync(file.path, enc);
parser.parseFuncFromString(content, { list: ['lang', 't'] }, (key, options) => {
options.defaultValue = key;
let hashKey=`k${crc32(key).toString(16)}`;
parser.set(hashKey, options);
});
done();
}
};
i18next-scanner 自動掃描代碼中的帶lang()格式的多語言。
i18n/index.js 參考
import Vue from "vue";
import VueI18n from "vue-i18n";
import iView from "iview";
import en from './en/translation.json'
import ch from "./cn/translation.json"
import { getLang } from "../utils/help";
import chLocale from "iview/dist/locale/zh-CN";
import enLocale from "iview/dist/locale/en-US";
import crc32 from 'crc/crc32';
let langType = getLang();
Vue.use(iView, {
locale: (() => {
if (langType == "en") {
return enLocale;
} else {
return chLocale;
}
})()
});
/* 語言包導入 */
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: getLang(), // set locale
messages: Object.assign({
ch: ch,
en: en
})
});
// switch (langType) {
// case 'en':
// import('./en/translation.json').then(msgs => {
// i18n.setLocaleMessage("en", msgs.default);
// })
// break;
// case 'ch':
// import('./cn/translation.json').then(msgs => {
// i18n.setLocaleMessage("ch", msgs.default);
// })
// break;
// default:
// break;
// }
export function lang(key) {
let hashKey = `k${crc32(key).toString(16)}`;
let words = i18n.t(hashKey);
if (words == hashKey) {
words = key;
console.log(key, "-沒翻譯")
}
return words;
};
export default i18n;
lang 方法封裝了i18n的多語言功能,差別是進一步對中文key進行crc32轉化,從而實現唯一且單一的key作為語音包的key的索取。
總結
通過以上的方式,可以實現中文作為代碼中的多語言的key,而且用中文作為key不會導致索引語音包導致的性能或索取不准確的問題,因為中文會先轉化為crc32的key然后對象的再去索引同樣以crc32為key的語音包,這樣可以實現中文作為代碼中的key,卻實際上還是以准備的hashkey來索引語音包。
i18next-scanner 是強大的node插件可以對代碼中的多語言進行自動索引。具體配置可以自己百度他的github。