11const ConcatStream = require ( 'concat-stream' )
2- const isRequire = require ( 'is-require' ) ( )
2+ const staticModule = require ( 'static-module' )
33const through = require ( 'through2' )
4- const falafel = require ( 'falafel' )
54const assert = require ( 'assert' )
65const fs = require ( 'fs' )
76
@@ -22,16 +21,27 @@ function cssExtract (bundle, opts) {
2221 addHooks ( )
2322
2423 function addHooks ( ) {
25- // run before the "debug" step in browserify pipeline
26- bundle . pipeline . get ( 'debug' ) . unshift ( through . obj ( write , flush ) )
2724 const writeStream = ( typeof outFile === 'function' )
2825 ? outFile ( )
29- : ConcatStream ( writeOutFile )
26+ : ConcatStream ( fs . writeFileSync . bind ( fs , outFile ) )
27+
28+ // run before the "debug" step in browserify pipeline
29+ bundle . pipeline . get ( 'debug' ) . unshift ( through . obj ( write , flush ) )
3030
3131 function write ( chunk , enc , cb ) {
32- const css = extract ( chunk )
33- writeStream . write ( css )
34- cb ( null , chunk )
32+ // A small performance boost: don't do ast parsing unless we know it's needed
33+ if ( String ( chunk . source ) . indexOf ( 'insert-css' ) === - 1 ) {
34+ return cb ( null , chunk )
35+ }
36+
37+ var sm = createStaticModule ( writeStream )
38+ sm . write ( chunk . source )
39+ sm . pipe ( ConcatStream ( function ( source ) {
40+ // chunk.source is expected to be a string
41+ chunk . source = String ( source )
42+ cb ( null , chunk )
43+ } ) )
44+ sm . end ( )
3545 }
3646
3747 // close stream and signal end
@@ -40,29 +50,10 @@ function cssExtract (bundle, opts) {
4050 cb ( )
4151 }
4252 }
43-
44- function writeOutFile ( buffer ) {
45- fs . writeFileSync ( outFile , buffer )
46- }
4753}
4854
49- // extract css from chunks
50- // obj -> str
51- function extract ( chunk ) {
52- // Do a performant check before building the ast
53- if ( String ( chunk . source ) . indexOf ( 'insert-css' ) === - 1 ) return ''
54-
55- const css = [ ]
56- const ast = falafel ( chunk . source , { ecmaVersion : 6 } , walk )
57- chunk . source = ast . toString ( )
58- return css . join ( '\n' )
59-
60- function walk ( node ) {
61- if ( ! isRequire ( node ) ) return
62- if ( ! node . arguments ) return
63- if ( ! node . arguments [ 0 ] ) return
64- if ( node . arguments [ 0 ] . value !== 'insert-css' ) return
65- css . push ( node . parent . arguments [ 0 ] . value )
66- node . parent . update ( '0' )
67- }
55+ function createStaticModule ( writeStream ) {
56+ return staticModule ( {
57+ 'insert-css' : writeStream . write . bind ( writeStream )
58+ } )
6859}
0 commit comments