-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
91 lines (69 loc) · 2.44 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
'use strict';
var CachingWriter = require('broccoli-caching-writer');
module.exports = LessCompiler;
LessCompiler.prototype = Object.create(CachingWriter.prototype);
LessCompiler.prototype.constructor = LessCompiler;
function uniq(value, index, arr) {
return arr.indexOf(value) === index;
}
function LessCompiler(sourceNodes, inputFile, outputFile, _options) {
if (!(this instanceof LessCompiler)) {
return new LessCompiler(sourceNodes, inputFile, outputFile, _options);
}
CachingWriter.call(this, Array.isArray(sourceNodes) ? sourceNodes : [sourceNodes], _options);
if (!outputFile) {
outputFile = inputFile.replace(/\.less/i, '.css');
}
// clone the _options hash to prevent mutating what was
// passed into us with fallback values. see issue #29
var options = require('lodash/merge')({}, _options);
if (options.sourceMap) {
if (typeof options.sourceMap !== 'object') {
options.sourceMap = {};
}
if (!options.sourceMap.sourceMapURL && !options.sourceMap.sourceMapFileInline) {
options.sourceMap.sourceMapURL = outputFile + '.map';
}
}
this.lessOptions = options;
this.sourceNodes = sourceNodes;
this.inputFile = inputFile;
this.outputFile = outputFile;
}
LessCompiler.prototype.build = function() {
var fs = require('fs');
var less = require('less');
var path = require('path');
var mkdirp = require('mkdirp');
var destFile = this.outputPath + '/' + this.outputFile;
mkdirp.sync(path.dirname(destFile));
var lessOptions = {
filename: require('include-path-searcher').findFileSync(this.inputFile, this.inputPaths),
paths: []
};
require('lodash/merge')(lessOptions, this.lessOptions);
lessOptions.paths = [path.dirname(lessOptions.filename)]
.concat(this.inputPaths)
.concat(lessOptions.paths)
.filter(uniq);
var data = fs.readFileSync(lessOptions.filename, 'utf8');
return less
.render(data, lessOptions)
.catch(function(err) {
if (!lessOptions || (lessOptions && !lessOptions.silent)) {
console.error(err.toString(lessOptions));
}
throw err;
})
.then(
function(output) {
fs.writeFileSync(destFile, output.css, { encoding: 'utf8' });
var sourceMapURL = lessOptions.sourceMap && lessOptions.sourceMap.sourceMapURL;
if (sourceMapURL) {
fs.writeFileSync(this.outputPath + '/' + sourceMapURL, output.map, {
encoding: 'utf8'
});
}
}.bind(this)
);
};