最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Webpack: How to exclude code from production bundle - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 15

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

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.

发布评论

评论列表(0)

  1. 暂无评论