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

时间:2016-11-02 00:41:43

标签: javascript webpack

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

如何让webpack删除每个版本的旧文件?

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

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

2 个答案:

答案 0 :(得分:23)

clean-webpack-pluginwebpack-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);
      }
  });

})

答案 1 :(得分:1)

我有一个build.js文件,我用node执行。在该文件中,我从webpack.config.js导入webpack的配置。我将所有配置保存在名为config的变量中。

require("shelljs/global");

var webpack = require('webpack');
var conf = require('./webpack.config.js');
var ora = require('ora');

var spinner = ora('chargement...');
spinner.start();
// I use the rm command that is provide by the module "shellsjs/global"
rm("-rf", "build");

webpack(conf, function(err, stats){
    spinner.stop();
    if(err) throw error
    process.stdout.write(stats.toString({
        color:true,
        modules:false,
        children:false,
        chunk: false,
        chunkModule:false
    }) + '\n')
})