forked from guybedford/require-less
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathless-builder.js
216 lines (183 loc) · 6.18 KB
/
less-builder.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
define(['require', './normalize'], function(req, normalize) {
var lessAPI = {};
var isWindows = !!process.platform.match(/^win/);
var normalizeWinPath = function(path) {
return isWindows ? path.replace(/\\/g, '/') : path;
};
var baseParts = normalizeWinPath(req.toUrl('base_url')).split('/');
baseParts[baseParts.length - 1] = '';
var baseUrl = baseParts.join('/');
function compress(css) {
var csso, csslen;
if (config.optimizeCss == 'none') {
return css;
}
if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) {
try {
csso = require.nodeRequire('csso');
}
catch(e) {
console.log('Compression module not installed. Use "npm install csso -g" to enable.');
return css;
}
try {
csslen = css.length;
if (typeof csso.minify === 'function') {
css = csso.minify(css).css;
} else {
css = csso.justDoIt(css);
}
console.log('Compressed CSS output to ' + Math.round(css.length / csslen * 100) + '%.');
return css;
}
catch(e) {
console.log('Unable to compress css.\n' + e);
return css;
}
}
console.log('Compression not supported outside of nodejs environments.');
return css;
}
function saveFile(path, data) {
if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) {
var fs = require.nodeRequire('fs');
fs.writeFileSync(path, data, 'utf8');
}
else {
var content = new java.lang.String(data);
var output = new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), 'utf-8'));
try {
output.write(content, 0, content.length());
output.flush();
}
finally {
output.close();
}
}
}
function escape(content) {
return content.replace(/(["'\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r");
}
var config;
var inject;
var siteRoot;
var less = require.nodeRequire('less');
var path = require.nodeRequire('path');
var layerBuffer = [];
var lessBuffer = {};
lessAPI.normalize = function(name, normalize) {
if (name.substr(name.length - 5, 5) == '.less')
name = name.substr(0, name.length - 5);
return normalize(name);
};
var absUrlRegEx = /^([^\:\/]+:\/)?\//;
lessAPI.load = function(name, req, load, _config) {
//store config
config = config || _config;
if (!siteRoot) {
siteRoot = path.resolve(
config.dir || path.dirname(
typeof config.out === 'string' ? config.out : ''
),
config.siteRoot || '.'
) + '/';
siteRoot = normalizeWinPath(siteRoot);
}
if (name.match(absUrlRegEx))
return load();
var fileUrl = normalizeWinPath(req.toUrl(name + '.less'));
//add to the buffer
var cfg = _config.less || {};
cfg.paths = [baseUrl].concat(cfg.paths || []);
cfg.filename = fileUrl;
cfg.async = false;
cfg.syncImport = true;
inject = cfg.inject;
//make it compatible with v1 and v2
var generation = less.version[0];
var renderer;
var cssGetter;
if (generation === 1) {
//v1, use parser and toCSS
var parser = new less.Parser(cfg);
renderer = function (input, cb) {
parser.parse.call(parser, input, cb, cfg);
};
cssGetter = function (tree) {
return tree.toCSS(config.less);
};
} else if (generation >= 2) {
//v2 or newer, use render and output
renderer = function (input, cb) {
less.render(input, cfg, cb);
};
cssGetter = function (output) {
return output.css;
};
}
renderer('@import (multiple) "' + path.relative(baseUrl, fileUrl) + '";', function (err, output) {
if (err) {
console.log(err + ' at ' + path.relative(baseUrl, err.filename) + ', line ' + err.line);
return load.error(err);
}
var css = cssGetter(output);
// normalize all imports relative to the siteRoot, itself relative to the output file / output dir
lessBuffer[name] = normalize(css, fileUrl, siteRoot);
load();
});
};
lessAPI.write = function(pluginName, moduleName, write) {
if (moduleName.match(absUrlRegEx))
return;
var css = lessBuffer[moduleName];
layerBuffer.push(css);
//use global variable to combine plugin results with results of require-css plugin
if (!global._requirejsCssData) {
global._requirejsCssData = {
usedBy: {less: true},
css: ''
};
} else {
global._requirejsCssData.usedBy.less = true;
}
var moduleContent = inject ? '' : "return '" + escape(compress(css)) + "'";
write.asModule(pluginName + '!' + moduleName, 'define(function(){' + moduleContent + '});');
};
lessAPI.onLayerEnd = function(write, data) {
if (inject === false) return;
//calculate layer css
var css = layerBuffer.join('');
if (config.separateCSS) {
console.log('Writing CSS! file: ' + data.name + '\n');
var outPath = config.dir ? path.resolve(config.dir, config.baseUrl, data.name + '.css') : config.out.replace(/(\.js)?$/, '.css');
outPath = normalizeWinPath(outPath);
css = normalize(css, siteRoot, outPath);
process.nextTick(function() {
if (global._requirejsCssData) {
css = global._requirejsCssData.css = css + global._requirejsCssData.css;
delete global._requirejsCssData.usedBy.less;
if (Object.keys(global._requirejsCssData.usedBy).length === 0) {
delete global._requirejsCssData;
}
}
saveFile(outPath, compress(css));
});
}
else {
if (css === '')
return;
write(
"(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})\n" +
"('" + escape(compress(css)) + "');\n"
);
}
//clear layer buffer for next layer
layerBuffer = [];
};
return lessAPI;
});