10
10
const fs = require ( 'fs' ) ;
11
11
const path = require ( 'path' ) ;
12
12
const SvgPrep = require ( 'svg-prep' ) ;
13
+ const { Compilation, sources } = require ( 'webpack' ) ;
14
+ const { RawSource } = sources ;
13
15
14
16
function SvgPrepPlugin ( options ) {
15
17
this . options = { } ;
@@ -23,28 +25,28 @@ function SvgPrepPlugin(options) {
23
25
}
24
26
25
27
SvgPrepPlugin . prototype . apply = function ( compiler ) {
26
- compiler . hooks . emit . tapAsync ( 'SvgPrepPlugin' , ( compilation , callback ) => {
27
- if ( ! this . options . source ) {
28
- return callback ( ) ;
29
- }
28
+ compiler . hooks . thisCompilation . tap ( SvgPrepPlugin . name , ( compilation ) => {
29
+ compilation . hooks . processAssets . tapPromise (
30
+ {
31
+ name : SvgPrepPlugin . name ,
32
+ stage : Compilation . PROCESS_ASSETS_STAGE_ADDITIONAL ,
33
+ } ,
34
+ async ( ) => {
35
+ if ( ! this . options . source ) {
36
+ return Promise . resolve ( ) ;
37
+ }
30
38
31
- // TODO: Keep track of file hashes, so we can avoid recompiling when none have changed
32
- let files = fs . readdirSync ( this . options . source ) . filter ( ( name ) => {
33
- return ! ! name . match ( / \. s v g $ / ) ;
34
- } ) . map ( ( name ) => path . join ( this . options . source , name ) ) ;
35
- SvgPrep ( files )
36
- . filter ( { removeIds : true , noFill : true } )
37
- . output ( ) . then ( ( sprited ) => {
38
- compilation . assets [ this . options . output ] = {
39
- source : function ( ) {
40
- return sprited ;
41
- } ,
42
- size : function ( ) {
43
- return sprited . length ;
44
- }
45
- } ;
39
+ // TODO: Keep track of file hashes, so we can avoid recompiling when none have changed
40
+ let files = fs
41
+ . readdirSync ( this . options . source )
42
+ . filter ( ( name ) => name . endsWith ( '.svg' ) )
43
+ . map ( ( name ) => path . join ( this . options . source , name ) ) ;
46
44
47
- callback ( ) ;
45
+ const sprited = await SvgPrep ( files )
46
+ . filter ( { removeIds : true , noFill : true } )
47
+ . output ( ) ;
48
+
49
+ compilation . emitAsset ( this . options . output , new RawSource ( sprited ) ) ;
48
50
} ) ;
49
51
} ) ;
50
52
}
0 commit comments