Why does my Webpack-cleanup-plugin delete my Exclude files?

Viewed 8455

Background: a simple one page react app + redux + express (in order to upload to heroku).
I already have index.html and images folder in the public folder. I want to run webpack to generate the styles.css and bundle.js that I used in my index.html. I want to use webpack-clean-up-plugin to remove the extra previous files every time I run build, but I don't want that to affect things like index.html and images folder.
According to the documentation: *Options If you want to keep some files in the output path, e.g. a stats.json file generated from some other plugins, use the exclude Array option. It accepts globbing as in minimatch.

// Do not delete stats.json, important.json, and everything in folder

new WebpackCleanupPlugin({
  exclude: ["stats.json", "important.js", "folder/**/*"],
})

Goal: to run webpack.prod.js so in the end the public folder has

  • index.html
  • bundle.js
  • bundle.js.map
  • styles.css
  • style.css.map
  • images(folder)

Webpack.config.prod.js:

const { CleanWebpackPlugin } = require('clean-webpack-plugin')  
output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    }, 
    plugins: [
        new MiniCssExtractPlugin({ 
            filename: "styles.css", 
            chunkFilename: "[id].css"}),
         new CleanWebpackPlugin({
         exclude: ["index.html", "images/*"],
        })
      ],  

Current result:
every time I npm run

"build:prod": "webpack --config webpack.config.prod.js --mode production",

I would get my index.html and images folder deleted. So where did I write wrong?

5 Answers

Instead of using exlude
use this option

cleanOnceBeforeBuildPatterns: ["**/*", "!stats.json","!important.js", "!folder/**/*"]

this works for me :) . Example:

new CleanWebpackPlugin({
    root: process.cwd(),
    verbose: true,
    dry: false,
    cleanOnceBeforeBuildPatterns: ["**/*", "!stats.json","!important.js", "!folder/**/*"],
})

Anyways, after reading more I decided not to use this plugin any more. Because people have been repeating similar issues as I have. And the author said on Mar 22 2018 that he doesn't have time to maintain any more that we should dismiss this plugin. view this on github

It's probably a path problem.you sould solve it with '__dirname'

You can use remove-files-webpack-plugin.

Configuration:

plugins: [
  new RemovePlugin({
    before: {
      // expects what your output folder is `dist`.
      test: [
        {
          folder: './dist',
          method: () => true
        }
      ],
      exclude: [
        './dist/index.html',
        './dist/images'
      ]
    }
  })
]

Note: i'm the creator of this plugin.

Apparently files not referenced explicitly are treated as stale and removed. This worked for me to skip cleaning files copied by CopyWebpackPlugin

new CleanWebpackPlugin({
   cleanStaleWebpackAssets: false,
}),
Related