Search code examples
javascriptnode.jswebpackuglifyjs

Strip dynamic requires from webpack


I have a code similar to this:

export default {
  something: true,
  mockData: process.env.USE_MOCK && require('./mocks/something.js').default
};

process.env.USE_MOCK is set with webpack.DefinePlugin to either true or false. I use this to start my app with USE_MOCK=true npm run dev or npm run dev to either run with mock data or not.

I want Webpack to remove these dynamic require in the build process with UglifyJS' dead code elimination, but I noticed that they remain there and so something.js will be in the built bundle.

In my case the output is similar to:

module.exports = {
  something: true,
  mockData: (false) && __webpack_require__(181).default
};

Is there a way how I can remove that import completely from the bundle?

Btw. I think something like this works:

let mockData;
if (process.env.USE_MOCK) {
  mockData = require('./mocks/something.js').default;
}
export default {
  something: true,
  mockData
};

I'd prefer the inline require though, as I've got that pattern quite a few times.


Solution

  • Try something like this:

    export default {
      something: true,
      mockData: process.env.USE_MOCK ? require('./mocks/something.js').default : undefined 
    };
    

    Or build module export separately:

    let module_export;
    module_export.something = true;
    
    if (process.env.USE_MOCK) {
      module_export.mockData = require('./mocks/something.js').default;
    }
    
    export module_export;