-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
92 lines (78 loc) · 2.46 KB
/
index.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
/**
* Loading modules
*/
const path = require('path');
const gutil = require('gulp-util');
const through = require('through2');
const assign = require('lodash.assign');
const postcss = require('postcss');
/**
* Loading internal plugins
*/
const cleanCritical = require('./plugins/cleanCritical.js');
const extractCritical = require('./plugins/extractCritical.js');
/**
* Set defaults
* @type {{selectors: Array}}
*/
const DEFAULT_OPTIONS = {
selectors: []
};
/**
* Exporting myself
* @param opts
*/
module.exports = function (opts) {
/**
* Set options
* @type {{selectors: Array}}
*/
opts = assign({}, DEFAULT_OPTIONS, opts || {});
if (!Array.isArray(opts.selectors)) {
throw new gutil.PluginError('gulp-critical-css', 'Option `selectors` is expected to be an array');
}
opts.selectors.every(function (selector) {
if (typeof selector !== 'string' && !(selector instanceof RegExp)) {
throw new gutil.PluginError('gulp-critical-css', 'Option `selectors` only supports `string` and `RegExp`');
}
return true;
});
/**
* The transformer
*/
return through.obj(function (file, enc, cb) {
// no file - no work
if (file.isNull()) {
cb(null, file);
return;
}
// no streams!
if (file.isStream()) {
cb(new gutil.PluginError('gulp-critical-css', 'Streaming not supported'));
return;
}
// I do not like to use try-catch but at the moment i don't know if its really needed so I keep it like in the boilerplate.
try {
// Create a filepath object to modify the filenames
var filePath = path.parse(file.path);
// Let postcss generate our critical and cleaned stylesheets
var cleanedCSS = postcss([cleanCritical(opts)]).process(file.contents.toString()).css;
var criticalCSS = postcss([extractCritical(opts), cleanCritical(opts)]).process(file.contents.toString()).css;
// Create the new files
var cleanedFile = file.clone();
var criticalFile = file.clone();
// update the original file content with the generated
cleanedFile.contents = new Buffer(cleanedCSS);
criticalFile.contents = new Buffer(criticalCSS);
// update the file paths/names
cleanedFile.path = path.join(filePath.dir, filePath.name + filePath.ext);
criticalFile.path = path.join(filePath.dir, filePath.name + ".critical" + filePath.ext);
// Pass the files on to the next step
this.push(cleanedFile);
this.push(criticalFile);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-critical-css', err));
}
cb();
});
};