1 | 'use strict';
|
2 |
|
3 | var nano = require('cssnano'),
|
4 | bufferFrom = require('buffer-from'),
|
5 | assign = require('object-assign'),
|
6 | PluginError = require('plugin-error'),
|
7 | Transform = require('stream').Transform,
|
8 | applySourceMap = require('vinyl-sourcemaps-apply'),
|
9 |
|
10 | PLUGIN_NAME = 'gulp-cssnano';
|
11 |
|
12 | module.exports = function (opts) {
|
13 | opts = opts || {};
|
14 | var stream = new Transform({objectMode: true});
|
15 |
|
16 | stream._transform = function (file, encoding, cb) {
|
17 | if (file.isNull()) {
|
18 | return cb(null, file);
|
19 | }
|
20 | if (file.isStream()) {
|
21 | var error = 'Streaming not supported';
|
22 | return cb(new PluginError(PLUGIN_NAME, error));
|
23 | } else if (file.isBuffer()) {
|
24 | return nano.process(String(file.contents), assign(opts, {
|
25 | map: (file.sourceMap) ? {annotation: false} : false,
|
26 | from: file.relative,
|
27 | to: file.relative
|
28 | })).then(function (result) {
|
29 | if (result.map && file.sourceMap) {
|
30 | applySourceMap(file, String(result.map));
|
31 | }
|
32 | file.contents = bufferFrom(result.css);
|
33 | this.push(file);
|
34 | cb();
|
35 | }.bind(this))
|
36 | .catch(function (error) {
|
37 | var errorOptions = {fileName: file.path};
|
38 | if (error.name === 'CssSyntaxError') {
|
39 | error = error.message + error.showSourceCode();
|
40 | errorOptions.showStack = false;
|
41 | }
|
42 |
|
43 |
|
44 | setImmediate(function () {
|
45 | cb(new PluginError(PLUGIN_NAME, error));
|
46 | });
|
47 | });
|
48 | }
|
49 | };
|
50 |
|
51 | return stream;
|
52 | };
|