Skip to content

Commit 0e7f613

Browse files
refactor: update svgprep plugin for webpack 5 (#1859)
1 parent 600cf40 commit 0e7f613

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

webpack/plugins/svg-prep.js

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
const fs = require('fs');
1111
const path = require('path');
1212
const SvgPrep = require('svg-prep');
13+
const { Compilation, sources } = require('webpack');
14+
const { RawSource } = sources;
1315

1416
function SvgPrepPlugin(options) {
1517
this.options = {};
@@ -23,28 +25,28 @@ function SvgPrepPlugin(options) {
2325
}
2426

2527
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+
}
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(/\.svg$/);
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

Comments
 (0)