1
1
const ConcatStream = require ( 'concat-stream' )
2
- const isRequire = require ( 'is-require' ) ( )
2
+ const staticModule = require ( 'static-module' )
3
3
const through = require ( 'through2' )
4
- const falafel = require ( 'falafel' )
5
4
const assert = require ( 'assert' )
6
5
const fs = require ( 'fs' )
7
6
@@ -22,16 +21,28 @@ function cssExtract (bundle, opts) {
22
21
addHooks ( )
23
22
24
23
function addHooks ( ) {
25
- // run before the "debug" step in browserify pipeline
26
- bundle . pipeline . get ( 'debug' ) . unshift ( through . obj ( write , flush ) )
27
24
const writeStream = ( typeof outFile === 'function' )
28
25
? 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 ) )
30
31
31
32
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 ( )
35
46
}
36
47
37
48
// close stream and signal end
@@ -40,29 +51,10 @@ function cssExtract (bundle, opts) {
40
51
cb ( )
41
52
}
42
53
}
43
-
44
- function writeOutFile ( buffer ) {
45
- fs . writeFileSync ( outFile , buffer )
46
- }
47
54
}
48
55
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
+ } )
68
60
}
0 commit comments