如何在 Angular 6 应用程序中通过 `ng build` 指定环境

How to specify environment via `ng build` in Angular 6 app

在Angular5、 我们可以使用

为不同的环境生成构建
ng build --prod --env=uat

迁移到 Angular 6 后上述命令抛出错误

Unknown option: '--env'

需要使用配置选项

ng build --prod --configuration=uat

ng build --prod -c uat

更多信息here

对于 ng 也提供与回答相同的选项

你可以尝试使用

ng 构建 ---prod

我已经在 Angular 6 项目中进行了测试。

ng build --prod --configuration=uat 似乎不起作用,因为它仅在您 运行 此命令时选择 uat 配置并忽略 --prod 标志并且不应用任何优化,例如 aot,缩小和升级等

运行 ng build --prod --configuration=uat 和 运行ning ng build --configuration=uat 的效果一样。为了应用任何其他配置选项,我们需要在 angular.json

的 uat 构建选项中明确添加它们
"configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true
        },
        "uat": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.test.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true
        }
      }
    }

你可以尝试使用:

ng build --configuration=uat
Prod: ng build --prod
Qa: ng build --configuration=qa

angular.json
"production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
},
"qa": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
              ]
}

PROD:
export const environment = {
  production: true,
  api : 'https://example.com'
}

QA:
export const environment = {
    production: true,
    api : 'https://example-Qa.com'
}

dev environment
export const environment = {
    production:false,
    api : 'https://example-dev.com'
}