|
| 1 | +const isRequire = require('is-require')() |
| 2 | +const through = require('through2') |
| 3 | +const falafel = require('falafel') |
| 4 | +const assert = require('assert') |
| 5 | +const fs = require('fs') |
| 6 | + |
| 7 | +module.exports = cssExtract |
| 8 | + |
| 9 | +// Extract CSS from a browserify bundle |
| 10 | +// obj -> null |
| 11 | +function cssExtract (bundle, opts) { |
| 12 | + opts = opts || {} |
| 13 | + |
| 14 | + var outFile = opts.out || opts.o || 'bundle.css' |
| 15 | + |
| 16 | + assert.equal(typeof bundle, 'object', 'bundle should be an object') |
| 17 | + assert.equal(typeof opts, 'object', 'opts should be an object') |
| 18 | + |
| 19 | + // every time .bundle is called, attach hook |
| 20 | + bundle.on('reset', addHooks) |
| 21 | + addHooks() |
| 22 | + |
| 23 | + function addHooks () { |
| 24 | + // run before the "debug" step in browserify pipeline |
| 25 | + bundle.pipeline.get('debug').unshift(through.obj(write, flush)) |
| 26 | + const writeStream = (typeof outFile === 'function') |
| 27 | + ? outFile() |
| 28 | + : fs.createWriteStream(outFile) |
| 29 | + |
| 30 | + function write (chunk, enc, cb) { |
| 31 | + const css = extract(chunk) |
| 32 | + writeStream.write(css) |
| 33 | + cb(null, chunk) |
| 34 | + } |
| 35 | + |
| 36 | + // close stream and signal end |
| 37 | + function flush (cb) { |
| 38 | + writeStream.end() |
| 39 | + cb() |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// extract css from chunks |
| 45 | +// obj -> str |
| 46 | +function extract (chunk) { |
| 47 | + const css = [] |
| 48 | + const ast = falafel(chunk.source, { ecmaVersion: 6 }, walk) |
| 49 | + chunk.source = ast.toString() |
| 50 | + return css.join('\n') |
| 51 | + |
| 52 | + function walk (node) { |
| 53 | + if (!isRequire(node)) return |
| 54 | + if (!node.arguments) return |
| 55 | + if (!node.arguments[0]) return |
| 56 | + if (node.arguments[0].value !== 'insert-css') return |
| 57 | + css.push(node.parent.arguments[0].value) |
| 58 | + node.parent.update('0') |
| 59 | + } |
| 60 | +} |
0 commit comments