从Angular中的生产环境中排除组件代码

时间:2018-04-04 08:58:43

标签: javascript angular webpack angular-cli

我想从Angular 5+中的生产版本中排除某些组件。到目前为止,我已阅读并了解环境变量的概念,但根据我的理解,这些概念在运行时可用。我正在寻找的是实际排除某些模块被导入,以便它们的代码不会进入生产构建(文件)。

我也不想拥有 <div *ngIf="isProduction">...</div>放置,我宁愿做的事情是这样的:

Component({ ... templateUrl: environment.production ? 'app.prod.html' : 'app.html' })

然而,由于Angular编译器的工作原理,这也是不可能的。

我想这个问题的答案是调整angular-cli,但鉴于没有好的文档(我能找到),我想知道某人是否有更好的想法?

1 个答案:

答案 0 :(得分:2)

对于那些正在寻求“不太可扩展”的解决方案的人。

解决方案适用于 Angular 5 / Angular 6 +

您可以通过在 angular.json 文件中添加每个文件对来根据要构建/服务的环境切换特定文件。

例如,如果仅在使用生产环境/配置时希望在应用程序组件中使用app.prod.html而不是app.html。

angular.json 中,将替换项添加到您希望替换的配置下的fileReplacements数组中:

{
  ...
  "projects": {
    ...
    "configurations": {
      "production": {
        ...
        "fileReplacements": [
          ...
          *** ADD YOUR REPLACEMENT FILES HERE ***
          ...
        ]
      }
    }
  }
}

使用以上示例:

{
  ...
  "projects": {
    ...
    "configurations": {
      "production": {
        ...
        "fileReplacements": [
          ...
          {
            "replace": "src/app/app.html",
            "with": "src/app/app.prod.html"
          }
          ...
        ]
      }
    }
  }
}

这不是一个很好的解决方案,因为您似乎将对要替换的每个文件执行此操作,但是仍然可以运行。


使用

构建或提供特定配置
ng serve --configuration=production
ng build --configuration=production