16

Before the next build, I want to remove the previous build because if we do not remove the old build, some change that did not generate the output file may not be found as soon as possible. I am tried to do this work using this command in the package.json right now:

"dev": "rm -rf src/bundle && webpack --mode development --config build/webpack.dev.config.js",

but I feel this way may be a little dangerous with the rm -rf command, any better suggetion?

Dolphin
  • 29,069
  • 61
  • 260
  • 539

2 Answers2

27

Check out the docs: https://webpack.js.org/guides/output-management/#cleaning-up-the-dist-folder

Add clean:true

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: {
  index: './src/index.js',
  print: './src/print.js',
},
plugins: [
  new HtmlWebpackPlugin({
    title: 'Output Management',
  }),
],
output: {
  filename: '[name].bundle.js',
  path: path.resolve(__dirname, 'dist'),
  clean: true
},

};

nerdess
  • 10,051
  • 10
  • 45
  • 55
  • Is there an easy way to ignore a certain file name from the clean? – mitchell Jun 30 '22 at 03:11
  • @mitchell why would you want to do that? Any time you run a build all the files that are needed get created by webpack and put into the build folder. – nerdess Jul 04 '22 at 08:30
2

I solved the problem as follows

  plugins: [
    new HtmlWebpackPlugin({
       template: path.join(__dirname, 'src', 'template.pug'),
       filename: 'index.html', 
    }),
    new FileManagerPlugin({
        events: {
          onStart: { 
             delete: [
              {
                source: path.join(__dirname,'dist/').replaceAll('\\','/'), 
                 options:{
                   force: true,
                   recursive : true,
                   },
               },
             ],
           },
        },
     })

since you need to specify the full path and replace all \ with / so that webpack sees the whole path