在 Angular 5 中根据环境切换开发模式和产品模式

switch development mode and product mode by environments in Angular 5

我的 angular-cli.json 有环境数组。

"environmentsSource": "environments/environment.ts"
"environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"

environment.ts,

export const environment = {
      production: false
};

environment.prod.ts

export const environment = {
      production: true
};

并且在main.ts,

if (environment.production) {
    enableProdMode();
}

但是我只有一个 package.josn 文件。

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build"

我有不同的环境,例如 dev/qa 和 prod。 url 不同,如何只为一个 package.json 文件切换模式?

构建和部署过程是自动进行的。我们无法在构建时更改设置。

您需要在 CLI 中引用 configuration

运行 产品环境的示例。

ng serve --configuration=prod

这会将 environment.ts 文件替换为 environment.prod.ts

您可以在环境文件中设置所有需要的变量(url,...)。

代码中只需要读取环境文件即可。它将被 angular CLI 配置参数取代。您可以在 angular.json 文件中设置参数。

"configurations": {
    "prod": {
        "fileReplacements": [
            {
                "replace": "apps/afh/src/environments/environment.ts",
                "with": "apps/afh/src/environments/environment.prod.ts"
            }
        ],
        ...
    }
}

main.ts中,我检查了document.location.host的值。如果它包含特定的子字符串,则 I

enableProdMode()