1010const fs = require ( 'fs' ) ;
1111const path = require ( 'path' ) ;
1212const SvgPrep = require ( 'svg-prep' ) ;
13+ const { Compilation, sources } = require ( 'webpack' ) ;
14+ const { RawSource } = sources ;
1315
1416function SvgPrepPlugin ( options ) {
1517 this . options = { } ;
@@ -23,28 +25,28 @@ function SvgPrepPlugin(options) {
2325}
2426
2527SvgPrepPlugin . 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+ }
3038
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 ) ) ;
4644
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 ) ) ;
4850 } ) ;
4951 } ) ;
5052}
0 commit comments