-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.js
79 lines (48 loc) · 1.8 KB
/
task.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
const minify = require('html-minifier').minify;
const glob = require('glob');
const _ = require('lodash');
const fs = require('fs-extra');
const path = require('path');
module.exports = (logger, dirname, config) => {
return () => {
return new Promise((resolve, reject) => {
// Validate config
if ( ! config.dir || ! config.outDir ) return reject(new Error('HTML minifier plugin misconfiguration! dir and outDir must be present.'));
// Empty outDir if necessary
if ( config.cleanOutDir ) {
fs.emptyDirSync(path.join(dirname, config.outDir));
}
// Search `config.dir` for `.html` files
glob('**/*.html', { cwd: path.join(dirname, config.dir) }, (error, files) => {
if ( error ) return reject(error);
const promises = [];
const finalOptions = _.cloneDeep(config);
delete finalOptions.dir;
delete finalOptions.outDir;
delete finalOptions.cleanOutDir;
logger(`Minifying ${files.length} files...`);
for ( const file of files ) {
promises.push(new Promise((resolve, reject) => {
// Read file
fs.readFile(path.join(dirname, config.dir, file), { encoding: 'utf8' }, (error, data) => {
if ( error ) return reject(error);
// Minify HTML
const result = minify(data, finalOptions);
// Write to file
fs.outputFile(path.join(dirname, config.outDir, file), result, error => {
if ( error ) return reject(error);
resolve();
});
});
}));
}
Promise.all(promises)
.then(() => {
logger(`All ${files.length} files were minified.`);
resolve();
})
.catch(reject);
});
});
};
};