minifier.js 867 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const uglify = require('uglify-js')
  2. const through2 = require('through2')
  3. /**
  4. * @description 压缩内联 wxs 脚本
  5. */
  6. function wxs () {
  7. return through2.obj(function (file, _, callback) {
  8. if (file.isBuffer()) {
  9. file.contents = Buffer.from(file.contents.toString().replace(/<wxs(.*?)>([\s\S]+?)<\/wxs>/, (_, $1, $2) => {
  10. return `<wxs${$1}>${uglify.minify($2, {
  11. fromString: true,
  12. mangle: {
  13. toplevel: true
  14. }
  15. }).code}</wxs>`
  16. }))
  17. }
  18. this.push(file)
  19. callback()
  20. })
  21. }
  22. /**
  23. * @description 压缩 json 文件
  24. */
  25. function json () {
  26. return through2.obj(function (file, _, callback) {
  27. if (file.isBuffer()) {
  28. file.contents = Buffer.from(JSON.stringify(JSON.parse(file.contents.toString())))
  29. }
  30. this.push(file)
  31. callback()
  32. })
  33. }
  34. module.exports = {
  35. wxs,
  36. json
  37. }