-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
50 lines (43 loc) · 1.34 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
'use strict';
const lessToJs = require('less-vars-to-js');
const camelcase = require('camelcase');
const loaderUtils = require('loader-utils');
const entries = require('object.entries');
module.exports = function(source) {
this.cacheable && this.cacheable();
const query = loaderUtils.parseQuery(this.query);
const camelCaseKeys = !!(query.camelCase || query.camelcase);
const resolveVariables = !!(query.resolveVariables || query.resolvevariables);
const varRgx = /^@/;
const vars = lessToJs(source);
const keys = Object.keys(vars);
if (!keys.length) {
this.emitWarning('Could not find any extractable less variables!');
}
if (resolveVariables) {
const followVar = (value) => {
if (varRgx.test(value)) {
// value is a variable
return followVar(vars[value]);
}
return value;
}
entries(vars).map((entry) => {
const key = entry[0];
const value = entry[1];
vars[key] = followVar(value);
});
}
const transformKey = (key) => {
let ret = key.replace(varRgx, '');
if (camelCaseKeys) {
ret = camelcase(ret);
}
return ret;
}
const cleanedVars = keys.reduce((prev, key) => {
prev[transformKey(key)] = vars[key];
return prev;
}, {});
return `module.exports = ${JSON.stringify(cleanedVars, true, 2)};\n`;
};