1 |
|
2 | "use strict";
|
3 | const path = require('path');
|
4 | const through = require('through2');
|
5 |
|
6 |
|
7 | const CleanCSS = require('../../vendor/clean-css/clean');
|
8 | const PluginError = require('./error');
|
9 |
|
10 | module.exports = (options, callback) => {
|
11 |
|
12 | let _callback = callback || (o => undefined);
|
13 |
|
14 | return through.obj(function (file, enc, cb) {
|
15 |
|
16 | let _options = Object.assign({}, options || {});
|
17 |
|
18 | if (file.isNull()) {
|
19 | return cb(null, file);
|
20 | }
|
21 | if (file.isStream()) {
|
22 | this.emit('error', new PluginError('gulp-clean-css', 'Streaming not supported!'));
|
23 | return cb(null, file);
|
24 | }
|
25 |
|
26 | if (file.sourceMap) {
|
27 | _options.sourceMap = JSON.parse(JSON.stringify(file.sourceMap));
|
28 | }
|
29 |
|
30 | const content = {
|
31 | [file.path]: {styles: file.contents ? file.contents.toString() : ''}
|
32 | };
|
33 | if (!_options.rebaseTo && _options.rebase !== false) {
|
34 | _options.rebaseTo = path.dirname(file.path);
|
35 | }
|
36 |
|
37 |
|
38 | new CleanCSS(_options).minify(content, (errors, css) => {
|
39 |
|
40 | if (errors) {
|
41 | return cb(errors.join(' '));
|
42 | }
|
43 |
|
44 | let details = {
|
45 | 'stats': css.stats,
|
46 | 'errors': css.errors,
|
47 | 'warnings': css.warnings,
|
48 | 'path': file.path,
|
49 | 'name': file.path.split(file.base)[1]
|
50 | };
|
51 |
|
52 | if (css.sourceMap) {
|
53 | details['sourceMap'] = css.sourceMap;
|
54 | }
|
55 | _callback(details);
|
56 |
|
57 | file.contents = Buffer.from(css.styles);
|
58 |
|
59 | if (css.sourceMap) {
|
60 | const iMap = JSON.parse(css.sourceMap);
|
61 | const oMap = Object.assign({}, iMap, {
|
62 | file: path.relative(file.base, file.path),
|
63 | sources: iMap.sources.map(mapSrc => path.relative(file.base, mapSrc))
|
64 | });
|
65 |
|
66 | }
|
67 | cb(null, file);
|
68 | });
|
69 | });
|
70 | };
|