UNPKG

1.28 kBJavaScriptView Raw
1var resolve = require('resolve').sync
2var nodePath = require('path')
3var fs = require('fs')
4var rework = require('rework')
5var reworkImport = require('rework-import')
6
7module.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 // replace with `require('insert-css')(/* css string */)`
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}