Skip to content

refactor: update svgprep plugin for webpack 5 #1859

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions webpack/plugins/svg-prep.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
const fs = require('fs');
const path = require('path');
const SvgPrep = require('svg-prep');
const { Compilation, sources } = require('webpack');
const { RawSource } = sources;

function SvgPrepPlugin(options) {
this.options = {};
Expand All @@ -23,28 +25,28 @@ function SvgPrepPlugin(options) {
}

SvgPrepPlugin.prototype.apply = function(compiler) {
compiler.hooks.emit.tapAsync('SvgPrepPlugin', (compilation, callback) => {
if (!this.options.source) {
return callback();
}
compiler.hooks.thisCompilation.tap(SvgPrepPlugin.name, (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: SvgPrepPlugin.name,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
async () => {
if (!this.options.source) {
return Promise.resolve();
}

// TODO: Keep track of file hashes, so we can avoid recompiling when none have changed
let files = fs.readdirSync(this.options.source).filter((name) => {
return !!name.match(/\.svg$/);
}).map((name) => path.join(this.options.source, name));
SvgPrep(files)
.filter({ removeIds: true, noFill: true })
.output().then((sprited) => {
compilation.assets[this.options.output] = {
source: function() {
return sprited;
},
size: function() {
return sprited.length;
}
};
// TODO: Keep track of file hashes, so we can avoid recompiling when none have changed
let files = fs
.readdirSync(this.options.source)
.filter((name) => name.endsWith('.svg'))
.map((name) => path.join(this.options.source, name));

callback();
const sprited = await SvgPrep(files)
.filter({ removeIds: true, noFill: true })
.output();

compilation.emitAsset(this.options.output, new RawSource(sprited));
});
});
}
Expand Down