-
Notifications
You must be signed in to change notification settings - Fork 5
/
css-import-visitor.js
43 lines (36 loc) · 1.06 KB
/
css-import-visitor.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
const { readFileSync } = require('fs');
const path = require('path');
const requireResolve = require('require-resolve');
const { defaultOptions } = require('./consts');
/**
* Visitor for `import '*.css'` babel AST-nodes
*/
function CssImport(cb) {
return (babelData, { file, opts = {} }) => {
const { node } = babelData;
errorBoundary(node.source.value, () => {
if (!node.source.value.endsWith(opts.ext || '.css')) return;
const { src } = requireResolve(node.source.value, path.resolve(file.opts.filename));
const css = readFileSync(src, 'utf8');
// TODO: load postcss options and plugins
const options = { ...defaultOptions, ...opts };
cb({
babelData,
src,
css,
importNode: { ...node, ...node.specifiers[0] },
options,
});
});
};
}
module.exports = CssImport;
function errorBoundary(cssFile, cb) {
try {
cb();
} catch (e) {
debugger; // eslint-disable-line no-debugger
console.error(`babel-plugin-transform-import-css: ${ cssFile }`, e);
throw e;
}
}