express: 添 压缩HTML / express-minify-html 功能

利用 express 压缩HTML
更新于: 2024-01-14 10:10:22

安装

yarn add express-minify-html

配置

自己在项目中用到的简单配置。

export const HTML_MINIFY_OPTIONS = {
  override: true,
  exception_url: false,
  htmlMinifier: {
    removeComments: true,
    collapseWhitespace: true,
    collapseBooleanAttributes: true,
    removeAttributeQuotes: true,
    removeEmptyAttributes: true
  }
};

项目

核心配置就这一句 app.use(minifyHTML(HTML_MINIFY_OPTIONS));

var express = require('express');
var minifyHTML = require('express-minify-html');
var app = express();

app.use(
  minifyHTML({
    override: true,
    exception_url: false,
    htmlMinifier: {
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeEmptyAttributes: true,
      minifyJS: true
    }
  })
);

app.get('hello', function (req, res, next) {
  res.render('helloTemplate', { hello: 'world' }, function (err, html) {
    // The output is minified, huzzah!
    console.log(html);
    res.send(html);
  });
});

参考