如何在webpack --watch中从build dir中删除旧文件?

Chr*_* W. 16 javascript webpack

当我webpack.config.js设置为观察我的源文件,并且输出文件包含散列时,每次构建成功完成时,都存在一组全新的构建文件.这很快就填满了建筑目录!

如何webpack删除每个构建中的旧文件?

module.exports = {
  ...
  watch: true,
  output: {
    filename: '[name]-[hash:8].js'
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以webpack-dev-server用来构建内存,但这不适合我当前的构建过程.

Chr*_* W. 24

也没有clean-webpack-plugin,webpack-shell-plugin能够满足这些要求,因为它只在整个webpack过程之前或之后运行,而不仅仅是在构建之后.

但是,使用该on-build-webpack插件,您可以在构建完成时运行任意函数.在此函数中,取消链接构建目录中尚未创建的所有文件.该assets对象被传递到函数中,并具有刚刚创建的资产集.

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);
      }
  });

})
Run Code Online (Sandbox Code Playgroud)

  • 我希望这对某人有所帮助,因为我花了很长时间才弄明白! (7认同)
  • 非常感谢@ChrisW.这节省了我的大量时间!;)避免弃用警告的另一个修改是将`fs.unlink`更改为`fs.unlinkSync`或为异常提供回调. (2认同)