-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (66 loc) · 2.05 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 fs = require('fs');
const p = require('path');
const jsonify = require('jsonify-css');
const exit = t => (path, state) => {
if (!isImportingCSS(path)) return;
const decls = getImportDecls(path);
const filepath = getFilepath(path, state);
const css = getCSS(filepath);
const styles = jsonify({ root: p.dirname(filepath) })(css);
const objify = obj => Array.isArray(obj)
? t.arrayExpression(obj.map(x => 'string' === typeof x
? t.stringLiteral(x)
: objify(x)))
: t.objectExpression(Object.keys(obj)
.map(k => t.objectProperty(
t.stringLiteral(k),
'object' === typeof obj[k]
? objify(obj[k])
: t.stringLiteral(obj[k])
)));
const memberImports = decls.member.map(x =>
t.variableDeclaration('var', [
t.variableDeclarator(
t.identifier(x.imported.name),
!(x.imported.name in styles)
? (x.imported.name === 'raw' ? t.stringLiteral(css) : t.identifier('undefined'))
: t.arrayExpression(styles[x.imported.name].map(objify))
)
]));
const fullImport = decls.full.map(x =>
t.variableDeclaration('var', [
t.variableDeclarator(
t.identifier(x.local.name),
objify(
styles.rule.concat(styles.media)
.reduce((a, b) => Object.assign({}, a, b), {})
))
]));
path.replaceWithMultiple([
...fullImport,
...memberImports,
]);
};
const isImportingCSS = path =>
'.css' === p.parse(path.node.source.value).ext;
const getImportDecls = path => ({
full: path.node.specifiers
.filter(x => x.type !== 'ImportSpecifier'),
member: path.node.specifiers
.filter(x => x.type === 'ImportSpecifier'),
});
const getFilepath = (path, state) => {
const dir = state.file.opts.filename[0] === '.'
? p.dirname(p.resolve(state.file.opts.filename))
: 'node_modules';
return p.resolve(dir, path.node.source.value);
};
const getCSS = filepath =>
fs.readFileSync(filepath, 'utf8');
module.exports = opts => ({
visitor: {
ImportDeclaration: {
exit: exit(opts.types)
}
}
});