-
Notifications
You must be signed in to change notification settings - Fork 15
/
minifier.js
91 lines (73 loc) · 2.08 KB
/
minifier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
var objectMerge = require('lodash.merge'),
minify = require('html-minifier').minify;
function minifyHTML(opts) {
var default_opts = {
override: false,
exception_url: false,
htmlMinifier: {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true
}
};
if (!opts) {
opts = {};
}
opts = objectMerge(default_opts, opts);
if (opts.exception_url.constructor !== Array) {
opts.exception_url = [ opts.exception_url ];
}
function minifier(req, res, next) {
var skip = false;
opts.exception_url.every(function(exception){
switch (true) {
case exception.constructor === RegExp:
skip = exception.test(req.url);
break;
case exception.constructor === Function:
skip = exception(req, res) || false;
break;
case exception.constructor === String:
skip = req.url.match(exception) ? true : false;
break;
default:
}
return !skip;
});
var sendMinified = function (callback) {
// No callback specified, just minify and send to client.
if (typeof callback === 'undefined') {
return function (err, html) {
if (err) {
return next(err);
}
html = minify(html, opts.htmlMinifier);
res.send(html);
}
} else {
// Custom callback specified by user, use that one
return function (err, html) {
if (html) {
html = minify(html, opts.htmlMinifier);
}
callback(err, html);
}
}
};
res.renderMin = function (view, renderOpts, callback) {
this.render(view, renderOpts, sendMinified(callback));
};
if (opts.override && !skip) {
res.oldRender = res.render;
res.render = function (view, renderOpts, callback) {
this.oldRender(view, renderOpts, sendMinified(callback));
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML;