-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
70 lines (55 loc) · 1.94 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
// node >= 8
// babel == 7
const t = require('@babel/types');
const CssImport = require('./css-import-visitor');
const {
jsToAst, jsStringToAst, constAst, postcss,
} = require('./helpers');
/* main() { */
module.exports = function(/*babel*/) {
// is plugin initialized?
// const initialized = false;
const pluginApi = {
manipulateOptions (options) {
// if (initialized) return options;
return options;
// e.g. { generateScopedName }
// const currentConfig = { ...defaultOptions, ...retreiveOptions(options, pluginApi) };
// TODO:
// require('./postcss-hook')(currentConfig)
// const initialized = true;
},
visitor: {
ImportDeclaration: {
exit: CssImport(({ src, css, options, importNode, babelData }) => {
const postcssOptions = { generateScopedName: options.generateScopedName };
const { code, classesMap } = postcss.process(css, src, postcssOptions, options.configPath);
// const jssObject = cssToJss({ code });
// writeJssFile(jssObject, src);
// issues: Fails for import statement with no name #2
if (importNode.local) {
babelData.replaceWithMultiple([
classesMapConstAst({ classesMap, importNode }),
putStyleIntoHeadAst({ code }),
]);
} else {
babelData.replaceWithMultiple([
putStyleIntoHeadAst({ code }),
]);
}
}),
},
},
};
return pluginApi;
};
/* } */
function classesMapConstAst({ importNode, classesMap }) {
// XXX: class-names API extending with jssObject (css-in-js object generated on source css)
const classesMapAst = jsToAst(classesMap);
const classesMapVarNameAst = t.identifier(importNode.local.name);
return constAst(classesMapVarNameAst, classesMapAst);
}
function putStyleIntoHeadAst({ code }) {
return jsStringToAst(`require('load-styles')(\`${ code }\`)`);
}