/
index.js
103 lines (83 loc) · 2.65 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
93
94
95
96
97
98
99
100
101
102
103
'use strict';
var gutil = require('gulp-util'),
chalk = require('chalk'),
fs = require('fs-extra'),
transform = require('stream').Transform,
_s = require('underscore.string'),
PLUGIN_NAME = 'gulp-toolkit';
//////////////////////////////
// Find
//////////////////////////////
var findTargets = function (file) {
var regex = new RegExp(/(\/\*\! \@\{target\:\s*?).*?([^"]*?)(\} \*\/)/gi),
replaceRegex = '',
matches = '',
match = '',
parts = '',
replace = '',
endString = '',
files = {},
cut = '',
start = 0,
end = 0,
result = {};
matches = file.match(regex);
for (var i in matches) {
match = matches[i];
regex = new RegExp(/(\/\*\! \@\{target\:\s*?).*?([^"]*?)(\} \*\/)/gi)
parts = regex.exec(match);
endString = '/*! {target:' + parts[2] + '}@ */'
start = file.indexOf(parts[0]);
end = file.indexOf(endString) + endString.length;
cut = file.slice(start, end);
file = file.slice(0, start - 1) + file.slice(end + 1);
cut = cut.replace(parts[0], '').replace(endString, '');
if (files[parts[2]]) {
files[parts[2]].push('\n'+cut);
}
else {
files[parts[2]] = [];
files[parts[2]].push('\n'+cut);
}
}
result.file = file;
result.files = files;
return result;
}
//////////////////////////////
// Export gulp-toolkit
//////////////////////////////
module.exports = function (options) {
var stream = new transform({ objectMode: true });
stream._transform = function (file, unused, done) {
if (file.isNull()) {
stream.push(file);
done();
return;
}
var targets = findTargets(String(file.contents));
var base = options !== undefined && options.base !== undefined && typeof options.base === 'string' ? options.base : file.base;
base = base.charAt(base.length - 1) !== '/' ? base += '/' : base;
for (var i in targets.files) {
var filename = _s.slugify(i) + '.css';
var contents = targets.files[i].join('');
gutil.log('Creating Critical file ' + chalk.magenta(filename));
fs.outputFile(base + filename, contents, {'flag': 'a'}, function (err) {
if (err) {
return new gutil.PluginError({
plugin: PLUGIN_NAME,
message: 'Error creating Critical file: ' + err
});
}
});
}
file.contents = new Buffer(targets.file);
stream.push(file);
if (Object.keys(targets.files).length) {
gutil.log('Removed Critical CSS from ' + chalk.magenta(file.path.replace(file.base + '/', '')));
}
done();
return;
}
return stream;
}