index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import path from 'path';
  2. import fs from 'fs';
  3. import mime from 'mime';
  4. export default class {
  5. constructor(c = {}) {
  6. this.setting = Object.assign({}, {
  7. css: true,
  8. html: false,
  9. output: 'dist'
  10. }, c);
  11. }
  12. apply(op) {
  13. const {
  14. code,
  15. file
  16. } = op;
  17. if (code && !/app\.js/.test(file)) {
  18. let reg = /(\.{0,2}\/)+?(\w+?\/)+(\S+?)\.(png|jpg|gif|jpeg)(\?\w*)?/gi;
  19. let imgPaths = code.match(reg) || [];
  20. imgPaths.map(imgPath => {
  21. //匹配(?|&)_origin后缀,不转换为base64
  22. let isorigin = imgPath.match(/(\?|\&)\_origin/gi)
  23. if(!!isorigin) {
  24. op.code = op.code.replace(isorigin[0],'')
  25. return
  26. }
  27. imgPath = imgPath.match(/(\.{0,2}\/)+?(\w+?\/)+(\S+?)\.(png|jpg|gif|jpeg)/gi)[0]
  28. let pathFile = path.join(process.cwd(), this.setting.path || '', imgPath);
  29. try {
  30. let bData = fs.readFileSync(pathFile);
  31. let base64Str = bData.toString('base64');
  32. let mimeType = mime.lookup(pathFile);
  33. let dataUri = `data:${mimeType};base64,${base64Str}`;
  34. op.code = op.code.replace(imgPath, `${dataUri}`);
  35. let delPath = pathFile.replace("src", this.setting.output);
  36. fs.unlink(delPath, err => {
  37. if(err) {
  38. console.log('[权限不足] ' + delPath);
  39. } else {
  40. console.log('[成功删除] ' + delPath);
  41. }
  42. })
  43. } catch (e) {
  44. console.error('读取图片失败:', pathFile);
  45. }
  46. });
  47. }
  48. op.next();
  49. }
  50. }