-
Notifications
You must be signed in to change notification settings - Fork 116
/
index.js
112 lines (100 loc) · 2.83 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
104
105
106
107
108
109
110
111
112
var fs = require('fs');
var path = require('path');
var less = require('less');
var through2 = require('through2');
var replaceExt = require('replace-ext');
var assign = require('object-assign');
var applySourceMap = require('vinyl-sourcemaps-apply');
var PluginError = require('plugin-error');
function inlineSources(map) {
if (map.sourcesContent) {
return Promise.resolve(map);
}
return Promise.all(
map.sources.map(function (source) {
return new Promise(function (resolve, reject) {
fs.readFile(source, 'utf8', function (err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
})
).then(
function (contents) {
map.sourcesContent = contents;
return map;
},
function () {
return map;
}
);
}
function renderLess(str, opts) {
return new Promise(function (resolve, reject) {
less.render(str, opts, function (err, res) {
if (err) {
reject(err);
} else {
var obj = {
result: res.css,
imports: res.imports,
};
if (opts.sourceMap && res.map) {
obj.sourcemap = JSON.parse(res.map);
inlineSources(obj.sourcemap).then(function (map) {
obj.sourcemap = map;
resolve(obj);
});
} else {
resolve(obj);
}
}
});
});
}
module.exports = function (options) {
// Mixes in default options.
var opts = assign({}, {
compress: false,
paths: []
}, options);
return through2.obj(function (file, enc, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new PluginError('gulp-less', 'Streaming not supported'));
}
var str = file.contents.toString();
// Injects the path of the current file
opts.filename = file.path;
// Bootstrap source maps
if (file.sourceMap || opts.sourcemap) {
opts.sourceMap = true;
}
renderLess(str, opts).then(function(res) {
file.contents = Buffer.from(res.result);
file.path = replaceExt(file.path, '.css');
if (res.sourcemap) {
res.sourcemap.file = file.relative;
res.sourcemap.sources = res.sourcemap.sources.map(function (source) {
return path.relative(file.base, source);
});
applySourceMap(file, res.sourcemap);
}
return file;
}).then(function(file) {
cb(null, file);
}).catch(function(err) {
// Convert the keys so PluginError can read them
err.lineNumber = err.line;
err.fileName = err.filename;
// Add a better error message
err.message = err.message + ' in file ' + err.fileName + ' line no. ' + err.lineNumber;
return cb(new PluginError('gulp-less', err));
});
});
};