index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. let WXMLParser = require('@leejim/wxml-parser');
  2. let defaultConfig = {
  3. comment: true,
  4. whitespace: true,
  5. }
  6. let minifier = function(source, options) {
  7. let str = '';
  8. let isAllSpace = (str) => /^\s+$/.test(str);
  9. options = Object.assign({}, defaultConfig, options);
  10. var parser = new WXMLParser({
  11. onopentag(name, attribs, isSelfClosing) {
  12. let attrStr = Object.entries(attribs).map(([key, val]) => val === '' ? key : `${key}="${val.replace(/"/g, '\'')}"`).join(' ');
  13. let hasAttr = attrStr.length > 0;
  14. str += `<${name}${hasAttr || isSelfClosing ? ' ' : ''}${attrStr}${isSelfClosing ? '/' : ''}>`;
  15. },
  16. oncomment(cmt) {
  17. if (!options.comment) {
  18. str += `<!--${cmt}-->`;
  19. }
  20. },
  21. ontemplate(tmp) {
  22. str += `{{${tmp}}}`;
  23. },
  24. ontext(text) {
  25. if (!options.whitespace) {
  26. str += text;
  27. return;
  28. }
  29. if (!isAllSpace(text)) {
  30. str += text.trim();
  31. }
  32. },
  33. onclosetag(tagname) {
  34. str += `</${tagname}>`;
  35. }
  36. });
  37. parser.write(source);
  38. return str;
  39. }
  40. module.exports = minifier;