首先安装依赖
pnpm install xlsx file-saver
创建translate.js文件
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 = /[\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`
)
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 = 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'
})
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]
}
})
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,
locale: getCurrentLanguage(),
fallbackLocale: supportedLanguages[0],
availableLocales: supportedLanguages,
messages: generateI18nMessages()
})
export default i18n
执行node命令
node src/config/translate.mjs./src/config/admin.xlsx'