webpack-uni-component-placeholder
Version:
79 lines (73 loc) • 2.98 kB
JavaScript
/**
* @Descripttion: uniapp生成componentPlaceholder数据到小程序json文件中
* @Author: Yuzi
* @WebSite: www.Yuzi.me
* @Date: 2023.12.09 10:00
* @LastEditors: Yuzi
* @LastEditTime: 2023.12.25 18:18
*/
const path = require('path')
const fs = require('fs')
// 获取input dir
const uniInputDir = process.env.UNI_INPUT_DIR
// 获取dist
const uniOutDir = process.env.UNI_OUTPUT_DIR
function initModule(dirPath) {
// 读取指定目录下的所有文件
const files = fs.readdirSync(dirPath);
// 遍历所有文件
files.forEach(file => {
const filePath = path.join(dirPath, file);
// 判断是否为目录
if (fs.statSync(filePath).isDirectory()) {
// 如果是目录,递归调用 initModule
initModule(filePath);
} else if (path.extname(file) === '.vue' || path.extname(file) === '.js') {
// 如果是 .vue 文件,则读取其内容
const data = fs.readFileSync(filePath, 'utf-8');
// 使用path.relative获取相对路径
const relativePath = path.relative(uniInputDir, filePath)
// 获取componentPlaceholder信息
const componentsMatch = data.match(/componentPlaceholder\s*[:=]\s*{([\s\S]*?)}/)
if (componentsMatch && componentsMatch[1]) {
/**
* 获取build路径后,将.vue后缀名修改成.json,获取打包后的json文件
* uniOutDir:uni build之后的路径
* pathDifference:对比路径
*/
const resultPath = (uniOutDir + '/' + relativePath).replace(/\.(vue|js)/g, '.json')
// 获取componentPlaceholder文件后,组成数组
let components = componentsMatch[1].trim()
.replace(/,\s*$/, '') // 删除最后一个号码
.replace(/\s+/g, '') // 替换所有空格制表符换行符
.replace(/(\w+):/g, '"$1":') // 以冒号结尾的字段转换成双引号
.replace(/'/g, '"') // 将所有字段单引号转换成双引号
let Obj = JSON.parse(`{${components}}`)
// 写入小程序json文件
fs.readFile(resultPath, 'utf8', (err, data) => {
if (err) {
return console.log('componentPlaceHolder文件读取失败,失败原因是:' + err)
} else {
let baseJSON = JSON.parse(data);
// 判断Obj,如果为空,则删除小程序json文件中的componentPlaceholder
baseJSON.componentPlaceholder = Obj
// 重写json文件
fs.writeFileSync(resultPath, JSON.stringify(baseJSON, null, 4))
}
})
}
}
})
}
class uniComponentPlaceholder {
apply(compiler) {
// 注册 done 钩子
compiler.hooks.done.tap('uniComponentPlaceholder', () => {
// 执行构建后任务
initModule(uniInputDir)
let currentTime = new Date().toLocaleTimeString()
console.log("---------" + currentTime + " 刷新-成功---------",)
})
}
}
module.exports = uniComponentPlaceholder;