Raz Buchnik
Raz Buchnik

Reputation: 8411

How to prevent CleanWebpackPlugin from removing static files

I am using CopyWebpackPlugin in order to copy static files to the distributed folder but CleanWebpackPlugin removes them when I am using --watch mode. So first time the files are getting copied, second time files are getting removed and not re-copied.

// webpack config
plugins: [
  new CopyWebpackPlugin([
    {
      from: resolvePath('static'),
      to: resolvePath(isCordova ? 'cordova/www/static' : 'www/static'),
    },
  ]),
  new CleanWebpackPlugin()
]

Is there any fix for these two modules two work alongside?

Upvotes: 1

Views: 1089

Answers (2)

ANTARA
ANTARA

Reputation: 830

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

new CleanWebpackPlugin({
   cleanStaleWebpackAssets: false,
}),

Upvotes: 0

Raz Buchnik
Raz Buchnik

Reputation: 8411

I have finally been created my own webpack plugin.

const shell = require('shelljs')
const path = require('path');

function resolvePath(dir) {
  return path.join(__dirname, '../../../', dir);
}

module.exports = class CleanPlugin {
  // Define `apply` as its prototype method which is supplied with compiler as its argument
  apply(compiler) {
    // Specify the event hook to attach to
    compiler.hooks.emit.tapAsync(
      'CleanPlugin',
      (compilation, callback) => {
        let command = `rm -rf ${resolvePath("cordova/www")}/*.json`
        shell.exec(command)
        callback()
      }
    )
  }
}

And use this just as following:

// require the module
const CleanPlugin = require('./webpack-plugins/clean-plugin/clean-plugin-class')

// inject in plugins array in webpack config file
new CleanPlugin()

As you can see it just runs a shell command on every rebuild (even on a watch mode). This shell command is very specific and I can manage this as I want.

If you have multiple or many shell commands you can use external file and put there all of the logic.

Upvotes: 1

Related Questions