Neither clean-webpack-plugin
, webpack-shell-plugin
is able to fulfill these requirements because it only runs before or after the entire webpack process, not just after build.
However With the on-build-webpack plugin you can run an arbitrary function when the build is completed. In this function, unlink all the files in your build dir that are weren't just created. The assets
object is passed into the function and has the set of assets just created.
const fs = require('fs');
const WebpackOnBuildPlugin = require('on-build-webpack');
const buildDir = '...path/to/your/build-dir/';
module.exports = {
watch: true,
new WebpackOnBuildPlugin(function(stats) {
const newlyCreatedAssets = stats.compilation.assets;
const unlinked = [];
fs.readdir(path.resolve(buildDir), (err, files) => {
files.forEach(file => {
if (!newlyCreatedAssets[file]) {
fs.unlink(path.resolve(buildDir + file));
unlinked.push(file);
}
});
if (unlinked.length > 0) {
console.log('Removed old assets: ', unlinked);
}
});
})
UPDATE: The original project is dead but here is an up-to-date fork as of 2020: https://github.com/artemdudkin/before-build-webpack. There is also https://github.com/hashicorp/prebuild-webpack-plugin from the well-known hashicorp organization.