-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.js
99 lines (61 loc) · 2.52 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const terser = require('terser');
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('JS 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 `.js` files
glob('**/*.js', { 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 JS
terser.minify(data, finalOptions)
.then(result => {
// Throw error
if ( result.error ) return reject(new Error(`JS minifier threw the following error:\n${result.error}`));
if ( result.warnings && result.warnings.length ) logger(`JS minifier threw the following warnings:\n${result.warnings.reduce((a, b) => `${a}\n${b}`)}`);
// Write to file
fs.outputFile(path.join(dirname, config.outDir, file), result.code, error => {
if ( error ) return reject(error);
// Write source map
if ( result.map && config.sourceMap ) {
fs.outputFile(path.join(dirname, config.outDir, file + '.map'), result.map, error => {
if ( error ) return reject(error);
resolve();
});
}
else resolve();
});
})
.catch(reject);
});
}));
}
Promise.all(promises)
.then(() => {
logger(`All ${files.length} files were minified.`);
resolve();
})
.catch(reject);
});
});
};
};