1 | var resolve = require('resolve').sync
|
2 | var nodePath = require('path')
|
3 | var fs = require('fs')
|
4 | var rework = require('rework')
|
5 | var reworkImport = require('rework-import')
|
6 |
|
7 | module.exports = function ({types: t}) {
|
8 | return {
|
9 | visitor: {
|
10 | CallExpression: function (path, state) {
|
11 | const callee = path.get('callee')
|
12 | const arg = path.get('arguments.0')
|
13 |
|
14 | if (callee.isIdentifier() &&
|
15 | callee.node.name === 'require' &&
|
16 | arg && !arg.isGenerated() &&
|
17 | /\.css$/.test(arg.node.value)) {
|
18 | const srcPath = nodePath.dirname(nodePath.resolve(state.file.opts.filename))
|
19 | const requireText = arg.node.value
|
20 | const absolutePath = resolve(requireText, {basedir: srcPath})
|
21 |
|
22 | const css = rework(fs.readFileSync(absolutePath, 'utf8'))
|
23 | .use(reworkImport({path: nodePath.dirname(absolutePath)}))
|
24 | .toString({compress: true})
|
25 |
|
26 |
|
27 | path.replaceWith(
|
28 | t.expressionStatement(
|
29 | t.callExpression(
|
30 | t.callExpression(t.identifier('require'), [t.stringLiteral('insert-css')]),
|
31 | [t.stringLiteral(css)]
|
32 | )
|
33 | )
|
34 | )
|
35 | }
|
36 | }
|
37 | }
|
38 | }
|
39 | }
|