Created
December 12, 2016 03:58
-
-
Save gmaclennan/ba69fb96c1dba95d15f66baf3d618190 to your computer and use it in GitHub Desktop.
Insert css with a babel plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var resolve = require('resolve').sync | |
var nodePath = require('path') | |
var fs = require('fs') | |
var rework = require('rework') | |
var reworkImport = require('rework-import') | |
module.exports = function ({types: t}) { | |
return { | |
visitor: { | |
CallExpression: function (path, state) { | |
const callee = path.get('callee') | |
const arg = path.get('arguments.0') | |
if (callee.isIdentifier() && | |
callee.node.name === 'require' && | |
arg && !arg.isGenerated() && | |
/\.css$/.test(arg.node.value)) { | |
const srcPath = nodePath.dirname(nodePath.resolve(state.file.opts.filename)) | |
const requireText = arg.node.value | |
const absolutePath = resolve(requireText, {basedir: srcPath}) | |
const css = rework(fs.readFileSync(absolutePath, 'utf8')) | |
.use(reworkImport({path: nodePath.dirname(absolutePath)})) | |
.toString({compress: true}) | |
// replace with `require('insert-css')(/* css string */)` | |
path.replaceWith( | |
t.expressionStatement( | |
t.callExpression( | |
t.callExpression(t.identifier('require'), [t.stringLiteral('insert-css')]), | |
[t.stringLiteral(css)] | |
) | |
) | |
) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment