const path = require('path') const fs = require('fs') class BuildLocales { constructor() { this.localesFolderPath = './src/locales' // 指定多语言源码目录 this.outputFileName = 'locales/index.json' // 输出构建后的多语言 } apply(compiler) { compiler.hooks.emit.tapAsync('BuildLocales', (compilation, callback) => { const locales = fs.readdirSync(this.localesFolderPath) const mergedData = {} locales.forEach(file => { if (path.extname(file) === '.json') { const localePath = path.join(this.localesFolderPath, file) // 文件路径 const lang = path.parse(localePath).name // 语言如en、zh-CN、sv-SE等 const langData = fs.readFileSync(localePath, 'utf8') // 语言文件中的多语言配置 const jsonData = JSON.parse(langData) // 转换为json数据 Object.assign(mergedData, { [lang]: jsonData }) // 语言作为key } }) const outputFilePath = path.join(path.resolve(__dirname, '../../dist/'), this.outputFileName) const outputData = JSON.stringify(mergedData, null, 2) const dirPath = path.dirname(outputFilePath) // 提取目录 if (!fs.existsSync(dirPath)) { // 判断是否存在目录 fs.mkdir(dirPath, { recursive: true }, err => { // 创建目录 if (err) { console.error('构建多语言文件报错:', err) } else { fs.writeFileSync(outputFilePath, outputData) // 写入文件 } }) } callback() }) } } const BuildLocalesPlugin = ({ wpChain }) => { wpChain.plugin('BuildLocales').use(BuildLocales) } module.exports = BuildLocalesPlugin