forked from mcmar/sass-values-loader
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
72 lines (54 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
65
66
67
68
69
70
71
72
const camelCase = require('lodash').camelCase
const fromPairs = require('lodash').fromPairs
const loaderUtils = require('loader-utils')
const generateModuleExportValues = require('./src/generateModuleExportValues')
const extractSassVariables = require('./src/extract.js')
module.exports = function (content) {
const self = this
const opts = loaderUtils.getOptions(self) || {}
const callback = this.async()
const version = this.version || 1
const resourcePath = this.resourcePath
const resolve = this.resolve.bind(this)
this.cacheable && this.cacheable()
const convertVariables = (variables) => {
if (opts.preserveKeys) {
return variables
}
return variables.map(([k, v]) => {
return [camelCase(k), v]
})
}
try {
extractSassVariables(resourcePath, resolve, content).then((result) => {
const dependencies = result.dependencies
const variables = convertVariables(result.variables)
// fromPairs will also eliminate duplicates for us
const defaultExport = generateModuleExportValues(fromPairs(variables))
// Create Module code
let module = ''
// Webpack 2+
if (version >= 2) {
// use Map to eliminate duplicates
new Map(variables).forEach((value, name) => {
const constExport = generateModuleExportValues(value)
// Force camelCase for module names
module += `export var ${camelCase(name)} = ${constExport}\n`
})
module += `export default ${defaultExport}\n`
// Webpack 1
} else {
module = `module.exports = ${defaultExport}\n`
}
// Register dependencies dynamically
dependencies.forEach((dependency) => {
self.addDependency(dependency)
})
callback(null, module)
}).catch((error) => {
callback(error)
})
} catch (error) {
callback(error)
}
}