使用ng build --prod剥离所有注释和console.log可能吗?

sea*_*nEd 33 angular-cli angular

我正在使用MEAN,Angular 2,Node/Express,Angular-CLI和ng build --prod构建我的应用程序,我对我的应用程序中的一次性注释代码和十亿次调试console.log语句进行了讽刺.有没有办法让构建过程在构建时删除所有注释和console.log语句?手动做的想法是可怕的!

Sud*_*kar 27

我有简单的解决方法.把这段代码放进去main.ts

if(env === 'prod') { // assuming you have env variable configured
  // check if window exists, if you render backend window will not be available 
  if(window){
      window.console.log = function(){};
   }
}  
Run Code Online (Sandbox Code Playgroud)

  • 惊讶的是这是这里公认的解决方案。这不会删除console.log。它只是简单地将`console.log`更改为不执行任何操作。这将影响当前窗口中运行的所有JavaScript,而不仅仅是您自己的。这是一个可怕的做法。对于webpack,更好的解决方案是在捆绑/最小化过程中从文件中剥离console.log调用。 (4认同)
  • 大声笑好主意,问题是我在服务器端代码中有更多console.log语句:P谢谢 (2认同)
  • 您也可以在服务器代码上执行相同的操作。将该代码放在“ server.js”中。但是不要附加到窗口,因为它在节点环境中不存在。 (2认同)

小智 13

只需将其添加window.console.log = function(){};到`

if (environment.production) {
    enableProdMode();
}`
Run Code Online (Sandbox Code Playgroud)

  • 我不会推荐这个,因为浏览器仍然执行占位符功能,这仍然是用户设备的 CPU 工作量。请参阅:https://www.codementor.io/brijmcq/angular-clear-all-of-your-console-logs-in-production-build-with-just-a-few-lines-of-code-cxcw30yqs#评论-sjclji9d8 (2认同)

Jan*_*Jan 5

您可以在 tslint 配置文件中使用ng lint标志--fixno-console规则。并将其挂接到包文件中的构建调用。

例如。: ... "prebuild": "ng lint --fix", "build": "ng build -prod", ...

并构建应用程序

npm run build

参考: https: //github.com/angular/angular-cli/wiki/lint

  • 小心使用“ngject”,因为你将被迫自己管理 webpack,并且逆转这个过程并不容易。 (4认同)
  • 另一种选择是使用 webpack。您可以通过点击“ngject”来生成配置并使用加载器“webpack-strip”https://www.npmjs.com/package/webpack-strip 希望它有帮助! (3认同)
  • 是的,但是“预构建”命令不会触发。您可以拨打两个电话:`ng lint --fix && ng build -prod` (2认同)
  • 我的错...`no-console`没有修复程序 https://palantir.github.io/tslint/rules/ (2认同)