如何在webpack --watch中从build dir中删除旧文件? [英] How to remove old files from the build dir when webpack --watch?

查看:391
本文介绍了如何在webpack --watch中从build dir中删除旧文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的 webpack.config.js 设置为监视我的源文件,并且输出文件包含散列时,每次构建成功完成一个全新的集合时建立的文件存在。这很快填满了构建目录!

When my webpack.config.js is set to watch my source files, and the output files contain a hash, then each time the build successfully completes an entirely new set of built files exists. This quickly fills up the build dir with cruft!

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

How do I make webpack delete the old files on each build?

module.exports = {
  ...
  watch: true,
  output: {
    filename: '[name]-[hash:8].js'
  }
  ...
}






我知道我可以使用 webpack-dev-server 构建内存但不适合我当前的构建过程。


I recognize I could use webpack-dev-server to build in memory but that doesn't fit my current build process.

推荐答案

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

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.

然而,使用 on-build-webpack 插件,您可以在构建完成后运行任意函数。在此函数中,取消链接构建目录中尚未创建的所有文件。 资产对象被传递到函数中,并且刚刚创建了一组资产。

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

})

这篇关于如何在webpack --watch中从build dir中删除旧文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆