import path from 'path'; import fs from 'fs'; import mime from 'mime'; export default class { constructor(c = {}) { this.setting = Object.assign({}, { css: true, html: false, output: 'dist' }, c); } apply(op) { const { code, file } = op; if (code && !/app\.js/.test(file)) { let reg = /(\.{0,2}\/)+?(\w+?\/)+(\S+?)\.(png|jpg|gif|jpeg)(\?\w*)?/gi; let imgPaths = code.match(reg) || []; imgPaths.map(imgPath => { //匹配(?|&)_origin后缀,不转换为base64 let isorigin = imgPath.match(/(\?|\&)\_origin/gi) if(!!isorigin) { op.code = op.code.replace(isorigin[0],'') return } imgPath = imgPath.match(/(\.{0,2}\/)+?(\w+?\/)+(\S+?)\.(png|jpg|gif|jpeg)/gi)[0] let pathFile = path.join(process.cwd(), this.setting.path || '', imgPath); try { let bData = fs.readFileSync(pathFile); let base64Str = bData.toString('base64'); let mimeType = mime.lookup(pathFile); let dataUri = `data:${mimeType};base64,${base64Str}`; op.code = op.code.replace(imgPath, `${dataUri}`); let delPath = pathFile.replace("src", this.setting.output); fs.unlink(delPath, err => { if(err) { console.log('[权限不足] ' + delPath); } else { console.log('[成功删除] ' + delPath); } }) } catch (e) { console.error('读取图片失败:', pathFile); } }); } op.next(); } }