node 翻译web前端国际化

63 阅读1分钟

一、项目格式

image.png

二、需要的资源 import fs from 'fs' import path from 'path' import ExcelJS from 'exceljs'

exceljs 需要安装依赖

npm install exceljs

三、翻译代码 1、创建语言包位置 多语言的配合放在一个lang文件夹 在lang的时候,定义好一个文件,例如:/lang/zh.js

image.png

翻译的时候,这里的做法是 以 /lang/zh.js为标准字段名称,然后复制其他语言的配套文件夹及其内容

2、根据语言包的中的一个语言为标准,创建其他语言包格式


// 复制文件夹
const langList = ['en', 'vi', 'ms', 'id', 'th', 'pt']
import { langList } from './config.js'

const copyFolderRecursive = (source, target) =>{
  // 创建目标文件夹
  fs.mkdirSync(target, { recursive: true })

  // 遍历源文件夹中的每个文件/子文件夹
  fs.readdirSync(source).forEach(name => {
    const sourcePath = path.join(source, name)
    const targetPath = path.join(target, name)
    const stat = fs.statSync(sourcePath)

    if (stat.isDirectory()) {
      // 复制子文件夹
      copyFolderRecursive(sourcePath, targetPath)
    } else {
      // 复制文件
      fs.copyFileSync(sourcePath, targetPath)
    }
  })
}
langList.forEach((item) => {
    // 创建文件夹,生成对应的语言文件
    copyFolderRecursive('./lang/zh', `./lang/${item}`)
})

3、把js文件读取成一个对象数据

// 复制文件
/**
 * @param {复制源文件路劲} sourceFilePath 
 * @param {复制成功后新文件路径} targetFilePath 
 * @param {替换的正则规则} reg 
 * @param {替换值} replaceValue 
 */
const copyFileAndChange = (sourceFilePath, targetFilePath, reg, replaceValue) => {
  fs.copyFileSync(sourceFilePath, targetFilePath)

  // 读取目标文件的内容
  let fileContent = fs.readFileSync(targetFilePath, 'utf8')

  // 修改文件内容
  fileContent = fileContent.replaceAll(reg, replaceValue)

  // 将修改后的内容写入目标文件
  fs.writeFileSync(targetFilePath, fileContent, 'utf8')

  // console.log(targetFilePath + '文件复制并内容修改成功')
}

const langListArr = langList.map(() => {
        return {}
  })
  const keyNameList = []
  // 循环语言列表
  for (let [index, ele] of langList.entries()) {
    // 判断文件存不存在,如果存在,刪除文件
    if (checkIfFolderExists(`./lang/${langList[index]}.${scriptType}`)) {
      fs.unlinkSync(`./lang/${langList[index]}.${scriptType}`)
      // 翻译内容
      console.log('删除语言主文件进度: ' + (index / (langList.length - 1) * 100).toFixed(2) + '%' )
    }
    // 复制一份
    copyFileAndChange(`./lang/zh.${scriptType}`, `./lang/${langList[index]}.${scriptType}`, './zh/', `./${langList[index]}/`)
    let { indexLang, importKeyValuePairs } = await getInitFileData(`./lang/${langList[index]}.${scriptType}`)
    langListArr[index] = Object.assign({}, indexLang, importKeyValuePairs)
    keyNameList[index] = Object.keys(importKeyValuePairs)
  }

4、读取表格数据

const workbook = new ExcelJS.Workbook()
  // 读取翻译表格的内容,
  workbook.xlsx.readFile(fileName)
    .then(async () => {
      // 获取第一个工作表
      const worksheet = workbook.worksheets[0]
})

5、把表格值替换对应的中文值

let worksheetArr = Array.from({ length: worksheet.rowCount + 1 })
      // 循环
      for (let [worksheetIndex] of worksheetArr.entries()) {
        let row = worksheet.getRow(worksheetIndex)
        for (let [index] of langListArr.entries()) {
          // 匹配中文字,替换
          langListArr[index] = await recursionReplace(langListArr[index], row.getCell(1).value, row.getCell(index + 2).value, row.getCell(2).value)
          
          // 替换读取的en.js vi.js等文件本来的中文字段
          replaceDataForFile(`./lang/${langList[index]}.${scriptType}`, row.getCell(1).value, row.getCell(index + 2).value, row.getCell(2).value)
        }
        // 翻译内容
        console.log('翻译进度: ' + (worksheetIndex / (worksheetArr.length - 1) * 100).toFixed(2) + '%' )
      }
      
      langListArr.forEach((item, index) => {
        console.log('生成文件进度: ' + (index / (langListArr.length - 1) * 100).toFixed(2) + '%' )
        createDataToJsList(keyNameList[index], item, `./lang/${langList[index]}/`)
      })