vue实现多语言切换(i18next-i18next-scanner)

实现思路

1,i18next  多语言转换插件

2,i18next-scanner 自动扫描代码中的中文

3,中文作为多语言的key,通过crc32转为语音包的key


第一步:准备好各种包(插件)

1. npm install crc -S

2. npm install vue-i18n -S

3. npm install i18next-scanner -D

下载完之后,开始创建配置文件,首先在package.json 同级目录下 创建js文件;i18next-scaner.config.js
js配置如下:

const fs = require('fs')// node自带 fs文件转换

const { crc32 } = require('crc')// 事先下载 npm install crc 类似哈希的转换格式

module.exports = {

input: [

'src/**/*.{js,vue}',

    // Use ! to filter out files or directories

    '!src/config/i18n/**',

    '!**/node_modules/**'

  ],

  output:'./', // 输出目录

  options: {

debug:true,

    func:false,

    trans:false,

    lngs: ['en', 'cn', 'dn'],

    defaultLng:'cn',

    resource: {

loadPath:'./src/config/i18n/{{lng}}/{{ns}}.json', // 输入路径

      savePath:'./src/config/i18n/{{lng}}/{{ns}}.json', // 输出路径

      jsonIndent:2,

      lineEnding:'\n'

    },

    removeUnusedKeys:false, // 移除未使用的key

    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)

/**

    * @param {list} array 指定扫描的标识

    */

    parser.parseFuncFromString(content, {list: ['lang'] }, (key, options) => {

options.defaultValue = key

// 将传入的文字转成配置的 key,不一定非用 crc,别的也行,如果内容不会影响 json 格式,不用也行

      let hashKey =`k${crc32(key).toString(16)}`

      parser.set(hashKey, options)

})

done()

}

}

上个图:

-------i18next-scaner.config.js配置完成--------
第二步,src目录下新建config文件夹,config文件夹内新建i18n文件夹,i18n文件夹内新建index.js文件,同时另外新建en文件夹,cn文件夹,如下图:

此时还不能进行npm run scan扫描翻译,还需要对 i18n里面的index.js配置如下:

import Vuefrom 'vue'

import VueI18nfrom 'vue-i18n'

import enfrom './en/translation.json'

import cnfrom './cn/translation.json'

import crc32from 'crc/crc32'

/* 语言包导入*/

Vue.use(VueI18n)

const i18n =new VueI18n({

 locale:'cn', // set locale 默认情况下是中文,使用cn文件下的语言

  messages: { en, cn }

})

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

-----------------index.js配置完成------------------------

上个图吧

第三步;都配置好了之后就开始在main.js进行引入对应的文件,如下图

第四步:main.js引入对应文件之后,在package.json里面的scripts对象里面配置"scan":"i18next-scanner",如图:


配置好了就可以在控制台实现自动扫描(只会扫描页面有携带标识的文字,比如{{ $lang('这是一个需要扫描转换的文字') }} ),扫描出来的文字会携带对应唯一的code值。扫描前提是页面的中文有添加标识,这样扫描工具才知道哪些文字需要翻译。直接上图:


最头疼就是如果页面超级多,需要每个页面添加翻译lang标识,贼烦,这是一个手工活,好鸡累!不过至少能实现功能  豁出去了,一个个页面加吧!加漏了后续再继续加!!!!!

最后一步::如何切换语言,页面给个按钮 点击直接调用this.$i18n.local = ‘en’ 切换成英文(其他)语言,根据自己想要的逻辑随意切换,这里就不多说了。有什么不明白或有错漏的 欢迎留言,指正(这是本人亲自做过两个项目并已经成功上线!切换语言是纯前端页面切换,如果后台也需要翻译,后续可根据后台返回来的语言,前端进行同步即可!)

你可能感兴趣的:(vue实现多语言切换(i18next-i18next-scanner))