-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
64 lines (53 loc) · 1.73 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
var sass = require('node-sass')
module.exports = function (source) {
// Get all variable names and camelCase them.
var varNames = getAllVariableNames(source).map(function (varName) {
return {
cssName: varName,
jsName: camelize(varName),
}
})
// Create a new source that has, appended to the original source, a list of
// classes named the same as the camel cased variables, each of which has a
// single property `value` that's set to the variable.
var newSource = source + '\n' + varNames.reduce(function (src, name) {
return src + '.' + name.jsName + '{value:$' + name.cssName + '}\n'
}, '')
// Compile the new source.
var result = sass.renderSync({
data: newSource,
includePaths: [this.context],
outputStyle: 'compressed',
})
var css = result.css.toString('utf-8')
// Extract the values of the variables into a JS map.
var retrieveValueRegExp = /\.(\w+)\{value:(.+?)\}/g
var varMap = getAllMatches(retrieveValueRegExp, css)
.reduce(function (map, matches) {
var className = matches[0]
var value = matches[1]
map[className] = value
return map
}, {})
return 'module.exports=' + JSON.stringify(varMap)
}
function getAllVariableNames(source) {
var variableNameRegExp = /\$([\w\-]+)/g
return getAllMatches(variableNameRegExp, source)
.map(function (x) { return x[0] })
}
function getAllMatches(regexp, text) {
var allMatches = []
var result
while ((result = regexp.exec(text)) !== null) {
allMatches.push(result.slice(1))
}
return allMatches
}
function camelize(text) {
var sectionStartRegExp = /((?:^\w)|(?:-\w))/g
var result = text.replace(sectionStartRegExp, function (letter, index) {
return letter.toUpperCase().replace('-', '')
})
return result[0].toLowerCase().concat(result.slice(1))
}