forked from HuasoFoundries/systemjs-less-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
less.js
102 lines (87 loc) · 2.85 KB
/
less.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
if (typeof window !== 'undefined') {
// Failing to set this will hide the DOM body
// See also http://stackoverflow.com/questions/35702313/whats-adding-style-type-text-cssbody-display-none-important-style
window.less = {
async: true
};
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var i = 0; i < styles.length; i++) {
if (!styles[i].hasAttribute("data-href")) {
continue;
}
styleIds.push(styles[i].getAttribute("data-href"));
}
var loadStyle = function (url, less_browser) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.responseText) { //request.status >= 200 && request.status < 400) {
// Success!
var responseData = request.responseText;
//render it using less
less_browser.render(responseData, {
filename: url,
rootpath: url.replace(/[^\/]*$/, ''),
relativeUrls: true
}).then(function (data) {
//inject it into the head as a style tag
var style = document.createElement('style');
style.textContent = data.css;
style.setAttribute('type', 'text/css');
//store original type in the data-type attribute
style.setAttribute('data-type', 'text/less');
//store the url in the data-href attribute
style.setAttribute('data-href', url);
head.appendChild(style);
resolve('');
});
} else {
// We reached our target server, but it returned an error
reject();
}
};
request.onerror = function (e) {
reject(e);
};
request.send();
});
};
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var j = 0; i < styleIds.length; j++) {
if (load.address === styleIds[j]) {
return '';
}
}
//var less_browser = require('less.js');
return this.import('./lessjs/less.browser.js', {
name: module.id
}).then(function (less_browser) {
return loadStyle(load.address, less_browser);
});
};
} else {
var getBuilder = function (loader) {
return loader.import('./less-builder.js', {
name: module.id
});
};
// setting format = 'defined' means we're managing our own output
exports.translate = function (load) {
load.metadata.format = 'defined';
};
exports.bundle = function (loads, opts) {
var _this = this;
if (_this.buildCSS === false) {
return '';
}
return getBuilder(_this)
.then(function (builder) {
return builder.bundle.call(_this, loads, opts);
});
};
}