【问题标题】:Exclude components code from production environment in Angular从 Angular 的生产环境中排除组件代码
【发布时间】:2018-04-04 08:58:43
【问题描述】:

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

我也不想拥有 <div *ngIf="isProduction">...</div>躺着,我更想做的是这样的:

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

但是,由于 Angular 编译器的工作方式,这也是不可能的。

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

【问题讨论】:

  • 花了一段时间寻找一个好的答案,但我似乎仍然找不到。 @Max101 你有没有找到比我在下面发布的更好的解决方案?

标签: javascript angular webpack angular-cli


【解决方案1】:

对于那些正在寻找*不那么可扩展*解决方案的人。

解决方案适用于 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

【讨论】:

  • 是的,我最终得出了同样的结论。我相信这是目前唯一支持的实现方式...
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 2018-06-04
  • 2013-08-24
  • 1970-01-01
  • 2018-08-21
相关资源
最近更新 更多