Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove old files from the build dir when webpack --watch? [duplicate]

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!

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

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

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

like image 543
Chris W. Avatar asked Nov 02 '16 00:11

Chris W.


2 Answers

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.

like image 103
Chris W. Avatar answered Oct 11 '22 14:10

Chris W.


I have a build.js file which I execute with node. In that file I import the configuration of webpack from the webpack.config.js. I save all configuration in a variable called 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')
})
like image 34
Yves Kipondo Avatar answered Oct 11 '22 14:10

Yves Kipondo