1 | 'use strict';
|
2 |
|
3 | const PluginError = require('plugin-error');
|
4 | const htmlmin = require('html-minifier');
|
5 | const through = require('through2');
|
6 |
|
7 | module.exports = options => {
|
8 | return through.obj(function(file, enc, next) {
|
9 | if (file.isNull()) {
|
10 | next(null, file);
|
11 | return;
|
12 | }
|
13 |
|
14 | const minify = (buf, _, cb) => {
|
15 | try {
|
16 | let contents = Buffer.from(htmlmin.minify(buf.toString(), options));
|
17 | if (next === cb) {
|
18 | file.contents = contents;
|
19 | cb(null, file);
|
20 | return;
|
21 | }
|
22 | cb(null, contents);
|
23 | next(null, file);
|
24 | } catch (err) {
|
25 | let opts = Object.assign({}, options, { fileName: file.path });
|
26 | let error = new PluginError('gulp-htmlmin', err, opts);
|
27 | if (next !== cb) {
|
28 | next(error);
|
29 | return;
|
30 | }
|
31 | cb(error);
|
32 | }
|
33 | };
|
34 |
|
35 | if (file.isStream()) {
|
36 | file.contents = file.contents.pipe(through(minify));
|
37 | } else {
|
38 | minify(file.contents, null, next);
|
39 | }
|
40 | });
|
41 | };
|