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,28 @@ 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 "label" step in browserify pipeline
29+ // this makes sure insert-css requires are found before plugins like bundle-collapser run
30+ bundle . pipeline . get ( 'label' ) . unshift ( through . obj ( write , flush ) )
3031
3132 function write ( chunk , enc , cb ) {
32- const css = extract ( chunk )
33- writeStream . write ( css )
34- cb ( null , chunk )
33+ // A small performance boost: don't do ast parsing unless we know it's needed
34+ if ( String ( chunk . source ) . indexOf ( 'insert-css' ) === - 1 ) {
35+ return cb ( null , chunk )
36+ }
37+
38+ var sm = createStaticModule ( writeStream )
39+ sm . write ( chunk . source )
40+ sm . pipe ( ConcatStream ( function ( source ) {
41+ // chunk.source is expected to be a string
42+ chunk . source = String ( source )
43+ cb ( null , chunk )
44+ } ) )
45+ sm . end ( )
3546 }
3647
3748 // close stream and signal end
@@ -40,29 +51,10 @@ function cssExtract (bundle, opts) {
4051 cb ( )
4152 }
4253 }
43-
44- function writeOutFile ( buffer ) {
45- fs . writeFileSync ( outFile , buffer )
46- }
4754}
4855
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- }
56+ function createStaticModule ( writeStream ) {
57+ return staticModule ( {
58+ 'insert-css' : writeStream . write . bind ( writeStream )
59+ } )
6860}
0 commit comments