-
Notifications
You must be signed in to change notification settings - Fork 72
/
index.js
67 lines (60 loc) · 2.09 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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
const { join, dirname } = require('path');
const {
compileWithVariablesSync,
} = require('../../lib/compile-scss-with-variables');
const idKey = '!!variables-from-scss!!';
const keyLength = idKey.length;
const forbiddenKeyNames = [
...Object.getOwnPropertyNames(Object.prototype),
'prototype',
];
module.exports = (babel) => ({
visitor: {
ImportDeclaration(path, state) {
if (path.node.source.value.startsWith(idKey)) {
const deconstructedAssignments = [];
const usedVariableNames = [];
const assignments = [];
for (const specifier of path.node.specifiers) {
if (specifier.type === 'ImportDefaultSpecifier') {
assignments.push(specifier.local.name);
} else if (specifier.type === 'ImportSpecifier') {
usedVariableNames.push(specifier.imported.name);
deconstructedAssignments.push(
specifier.imported.name === specifier.local.name
? specifier.local.name
: `${specifier.imported.name}: ${specifier.local.name}`
);
}
}
const importTarget = join(
dirname(state.file.opts.filename),
path.node.source.value.substring(keyLength)
);
const { variables } = compileWithVariablesSync(importTarget);
// If no default specifier is used, reduce the variables to only those needed
const importedVariables =
assignments.length === 0
? usedVariableNames.reduce((acc, name) => {
if (!forbiddenKeyNames.includes(name))
acc[name] = variables[name];
return acc;
}, {})
: variables;
if (deconstructedAssignments.length > 0)
assignments.push(`{ ${deconstructedAssignments.join(', ')} }`);
path.replaceWith(
babel.template.statement.ast(
`const ${assignments.join(', ')} = ${JSON.stringify(
importedVariables
)};`
)
);
}
},
},
});