forked from yuguo/gulp-import-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (53 loc) · 1.73 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
'use strict';
var gutil = require('gulp-util'),
path = require('path'),
rework = require('rework'),
reworkImporter = require('rework-importer'),
through = require('through2');
// Consts
var PLUGIN_NAME = 'gulp-import-css';
module.exports = function() {
return through.obj(function(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
try {
var processedCss = rework(String(file.contents), 'utf-8')
.use(reworkImporter({
path: file.path,
base: file.base,
preProcess: function(ast, options) {
return ast
.use(rework.url(function(url) {
var srcDir,
resourcePath,
destDir;
if (isAbsoluteUrl(url) || isRootRelativeUrl(url)) {
return url;
}
// rebase relative url(...) found in CSS to be imported
// @import url(...) handled by rework-importer; not passed through here
srcDir = path.dirname(options.path);
resourcePath = path.resolve(srcDir, url);
destDir = path.dirname(file.path);
return path.relative(destDir, resourcePath);
}));
}
}))
.toString();
} catch(err) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
return cb();
}
file.contents = new Buffer(processedCss);
this.push(file);
cb();
});
};
function isAbsoluteUrl(url) {
return (/^[\w]+:\/\/./).test(url);
}
function isRootRelativeUrl(url) {
return url.charAt(0) === '/';
}