Search code examples
javascriptwebpackwebpack-2uglifyjstree-shaking

Conditional require file in webpack


I want to bundle the files into my production build only if it is not for DEBUG;

So I've use webpack.DefinePlugin and set the variable DEBUG === true.

Also config webpack.UglifyJsPlugin with default options

And in the js file, I do like this:

const A = DEBUG === true ? null : require('./some-debug.js');
//do things with A, for example
console.log(A)

I checked the final bundle file, A is replaced with null (so DefinePlugin is working fine), but the content of some-debug.js file is still in the bundle js.

Is it possible to let webpack not require the file?

ps: I think I can use resolve.alias to resolve './some-debug.js' --> undefined. But I want to keep my webpack.config.js generic, dont' want to apply too many resolve.alias entries.

Thanks


Solution

  • It doesn't work with ternary operator.

    let A;  
    if (DEBUG === true) {
      A = require('./some-debug.js');
    }