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

标签 javascript angular webpack angular-cli

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

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

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

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

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

最佳答案

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

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

关于javascript - 从 Angular 的生产环境中排除组件代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49646814/

相关文章:

javascript - 将参数传递给 Vuex 中的 getter

angular - 如何从 cdkPortal 中的内容获取 ViewChild

reactjs - ReactDOM RSS renderToString 制作错误

javascript - 如何在 React 中延迟加载 js 文件(针对多语言应用程序)

javascript - jQuery 字符串包含操作?

javascript - 使用 ajax 无法在灯箱中打开图像

Angular 导航强制新组件

webpack 找不到节点模块 ('bootstrap-multiselect' )

javascript - jQuery UI 可排序 : load order from array

html - Angular - 使用带 ngModel 的日期管道