-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.js
More file actions
100 lines (61 loc) · 2.57 KB
/
task.js
File metadata and controls
100 lines (61 loc) · 2.57 KB
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
100
const CleanCSS = require('clean-css');
const fs = require('fs-extra');
const path = require('path');
const _ = require('lodash');
const glob = require('glob');
module.exports = (logger, dirname, config) => {
return () => {
return new Promise((resolve, reject) => {
// Validate config
if ( ! config.dir || ! config.outDir ) return reject(new Error('Minify CSS plugin misconfiguration! dir and outDir must be present.'));
// Empty outDir if necessary
if ( config.cleanOutDir ) {
fs.emptyDirSync(path.join(dirname, config.outDir));
}
const finalOptions = _.cloneDeep(config);
delete finalOptions.dir;
delete finalOptions.outDir;
delete finalOptions.cleanOutDir;
delete finalOptions.returnPromise;
const minifier = new CleanCSS(finalOptions);
// Search `config.dir` for `.css` files
glob('**/*.css', { cwd: path.join(dirname, config.dir) }, (error, files) => {
if ( error ) return reject(error);
const promises = [];
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 CSS
const result = minifier.minify(data);
// Throw errors
if ( result.errors.length ) return reject(new Error(`CSS minifier threw the following errors:\n${result.errors.reduce((a, b) => `${a}\n${b}`)}`));
// Log warnings
if ( result.warnings.length ) logger(`CSS 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.styles, error => {
if ( error ) return reject(error);
// Write sourcemaps
if ( result.sourceMap && config.sourceMap ) {
fs.outputFile(path.join(dirname, config.outDir, file + '.map'), result.sourceMap, error => {
if ( error ) return reject(error);
resolve();
});
}
else resolve();
});
});
}));
}
Promise.all(promises)
.then(() => {
logger(`All ${files.length} files were minified.`);
resolve();
})
.catch(error);
});
});
};
};