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.
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.
Share Improve this question edited May 9, 2024 at 1:47 Simon E. 58.5k18 gold badges144 silver badges137 bronze badges asked Mar 17, 2019 at 10:58 Jon SudJon Sud 11.6k31 gold badges102 silver badges226 bronze badges2 Answers
Reset to default 15In 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
Webpack has a mode
setting, which allows you to switch between development and production builds.
In your code you can use process.env.NODE_ENV
to find out wether you are in production or not, Webpack uses that property to eliminate "production dead code":
// declare variable everywhere to prevent unresolvable variable references
let onlyInDev = "";
// The following should be shaken away by webpack
if(process.env.NODE_ENV === "development") {
onlyInDev = "test";
}
If the value is a sensitive information that should not be leaked to your production build, I would search for it in the bundle to make sure that it doesn't get leaked if the building pipeline changes.