0

Angular Workspace 配置指南的构建配置部分讨论了如何在同一个应用程序中管理各种配置。

就我而言,我决定为每个客户创建一个配置:

// angular.json excerpt
"architect": {
    "build": {
        "configurations": {
            "customer-1": {
                "fileReplacements": [
                    {
                    "replace": "src/environments/environment.ts",
                    "with": "src/environments/environment.customer-1.ts"
                    }
                ]
            },
            "customer-2": {
                "fileReplacements": [
                    {
                    "replace": "src/environments/environment.ts",
                    "with": "src/environments/environment.customer-2.ts"
                    }
                ]
            },
        }
    },
    "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "configurations": {
            "customer-1": {
                "browserTarget": "my-app:build:customer-1"
            },
            "customer-2": {
                "browserTarget": "my-app:build:customer-2"
            },
}

我使用环境文件来管理各种客户特定的设置和production标志:

// environment.customer-1.ts excerpt
const environment = {
  production: true,
  customer: "Customer 1",
};


// environment.customer-2.ts excerpt
const environment = {
  production: true,
  customer: "Customer 2",
};

最后,我需要一种方法来确定应用程序是否是使用ng serveng build命令启动的,以便在应用程序模块中导入一些模拟的提供程序。

我尝试使用该environment.production标志,但显然它总是正确的:

import { environment } from '../environments/environment';

@NgModule({
  providers: [
    environment.production // is always true since I've set the flag in all customer-specific environment.ts files
       ? []
       : nonProductionProviders,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我想出支持这种情况的唯一方法是创建单独的environment.ts文件以及匹配的配置,例如

  • /src/environment.customer-1-dev.ts
  • /src/environment.customer-1-prod.ts
// angular.json excerpt
"architect": {
    "build": {
        "configurations": {
            "customer-1-dev": {
                "fileReplacements": [
                    {
                    "replace": "src/environments/environment.ts",
                    "with": "src/environments/environment.customer-1-dev.ts"
                    }
                ]
            },
            // etc.

有一个更好的方法吗?传递一个额外的标志或至少扩展配置的能力会很好。

4

1 回答 1

0

我认为你现在拥有的是最好的方法。环境文件用于在编译时已知的配置,这正是您的场景

您还可以有一个脚本src/environments/environment.customer-XX.ts在运行之前修改文件中的值 use ng serve,但您可能会错误地将修改后的文件提交到 git 上。

您还可以有一些动态 json 配置(修改后的构建),您可以在引导您的应用程序之前通过 http 调用检索这些配置,以查看是否使用了构建或服务,但对于您的情况来说,这可能是矫枉过正。

目前无法从angular.json文件中扩展配置。有这个功能请求可能会让很多人满意,但我认为它还没有被处理。

于 2019-07-08T14:55:04.233 回答