首先安装依赖
pnpm install xlsx file-saver
创建translate.js文件
/* eslint-disable no-useless-escape */
/* eslint-disable no-control-regex */
import fs from 'node:fs'
import path from 'node:path'

import * as XLSX from 'xlsx'

export default function useParseLang() {
  const filePath = process.argv[2]
  if (!filePath) {
    console.error('文件不存在')
    return
  }
  const inputPath = path.resolve(filePath)
  console.log('翻译文件', inputPath)
  fs.readFile(inputPath, 'binary', (err, data) => {
    if (err) {
      throw new Error(err)
    }
    const workBook = XLSX.read(data, { type: 'binary', cellDates: true })
    // const reg = /([^\x00-\xff])|([\?\.\(\)\$\:\u00A0\s,'-])|[0-9]/g // 去除key中的特殊字符数字,所有全角符号和部分半角符号
    const reg = /[\s\u00A0]+/g // 匹配一个或多个连续的空格字符或非断空格
    workBook.SheetNames.forEach(name => {
      const workSheet = workBook.Sheets[name]
      console.log('workSheet: ', workSheet)
      const rawList = XLSX.utils.sheet_to_json(workSheet, { header: 1 })
      const enObj = {}
      const zhObj = {}
      const zhPath = path.join(
        process.cwd(),
        `/src/locales/lang/zh-CN/${name}.json`
      )
      const enPath = path.join(
        process.cwd(),
        `/src/locales/lang/en-US/${name}.json`
      )
      // if (name === 'common') {
      //   zhPath = path.join(
      //     process.cwd(),
      //     `/packages/website/lang/zh-CN/website.json`
      //   )
      //   enPath = path.join(
      //     process.cwd(),
      //     `/packages/website/lang/en/website.json`
      //   )
      // } else {
      // }
      rawList.forEach(item => {
        const valueArr = item.slice(item.length - 2)
        const keyArr = item.slice(0, item.length - 2)
        const parseKeyArr = keyArr
          .map(key => {
            const tem = key.charAt(0).toLowerCase() + key.slice(1)
            return tem.replaceAll(reg, '')
          })
          .filter(Boolean)
        parseKeyArr.unshift(name)
        // const keyResult = name + '.' + parseKeyArr.join('.')
        const keyResult = parseKeyArr.join('.')
        zhObj[keyResult] = valueArr[0]
        enObj[keyResult] = valueArr[1]
        console.log('zhObj: ', zhObj, enObj)
      })

      fs.writeFileSync(zhPath, JSON.stringify(zhObj, null, 2))
      fs.writeFileSync(enPath, JSON.stringify(enObj, null, 2))
    })
  })
}

useParseLang()

local/index.ts
import { createI18n } from 'vue-i18n'

import { storage } from '@/utils/sessionStorage'

const supportedLanguages: Language[] = ['zh-CN', 'en-US']
function generateI18nMessages() {
  const messages: { [key in Language]?: Record<string, any> } = {}
  const modules = import.meta.glob(`./lang/**/*.json`, {
    eager: true,
    import: 'default'
  })
  //1. 遍历所有文件,获取语言代码,采用平铺的方式
  Object.keys(modules).forEach(key => {
    const moduleMessages = modules[key] as any
    const [lang, _] = key.replace('./lang/', '').replace('.json', '').split('/')
    console.log(_)
    if (!messages[lang]) {
      messages[lang] = {}
    }
    for (const key2 in moduleMessages) {
      messages[lang][key2] = moduleMessages[key2]
    }
  })
  // 2.处理的是en-US下有多文件层级的情况
  // function getMsg(obj, arr: string[]) {
  //   if (!arr.length) {
  //     return
  //   }
  //   const item = arr.shift()!
  //   console.log('item: ', item)
  //   let next = arr.length === 0 ? moduleMessages : {}
  //   if (obj[item]) {
  //     next = obj[item]
  //   }
  //   obj[item] = next
  //   getMsg(next, arr)
  // }
  // getMsg(messages, arr)
  return messages
}
const getCurrentLanguage = () => {
  //设置
  const navLang = navigator.language //系统语言
  console.log('navLang: ', navigator, navLang)
  const storageLang = storage.get('lang') //本地存储
  console.log('storageLang: ', storageLang)
  const localLang = navLang.indexOf('zh') !== -1 ? 'zh-CN' : 'en-US' || 'zh'
  let langCode = 'zh-CN'
  if (storageLang) {
    langCode = storageLang?.indexOf('zh') !== -1 ? 'zh-CN' : 'en-US'
  } else {
    langCode = localLang
  }
  storage.set('lang', langCode)
  return langCode
}

const i18n = createI18n({
  legacy: false, // 如果要支持compositionAPI,此项必须设置为false;
  // globalInjection: true, // 全局注册$t方法
  locale: getCurrentLanguage(),
  fallbackLocale: supportedLanguages[0],
  availableLocales: supportedLanguages,
  messages: generateI18nMessages()
})

export default i18n

执行node命令
node src/config/translate.mjs./src/config/admin.xlsx'

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部