Search code examples
javascriptnode.jswebpack

Webpack: How to exclude code from production bundle


How do I exclude specific lines of typescript code from a webpack bundle during build-time?

For example, I have this line of code in app.ts (nodejs application):

const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa';

When I build my app using webpack configuration, I want to exclude this code.


Solution

  • In webpack version 4 you are able to set mode: 'production' in your webpack config. (https://webpack.js.org/concepts/mode/)

    So in your source code you can use the following:

    if (process.env.NODE_ENV === 'development') {
        const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa';
        ...
    }
    

    In conclusion all code inside if and ifs themself will be automatically removed during building your bundle