如何检测 Angular 16 中的运行配置?

问题描述 投票:0回答:1

这个问题可能看起来微不足道,但我没有找到任何答案。很多人引用这个答案,我认为它不再有效。

问题如下:从 Angular 16 开始(我没有检查以前的版本),命令

ng new project
将不再生成环境配置,运行应用程序不需要它。

我们可以使用

ng generate environments
来生成环境脚手架,但它看起来会与以前不同:它将是一堆普通的打字稿文件,将取代
envinroment.ts
文件。没有可用的
production
房产。

angular.json
中提供了一些配置,并且可以添加更多配置。默认属性如下所示:

      "configurations": {
        "production": {
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "500kb",
              "maximumError": "1mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "2kb",
              "maximumError": "4kb"
            }
          ],
          "outputHashing": "all"
        },
        "development": {
          "buildOptimizer": false,
          "optimization": false,
          "vendorChunk": true,
          "extractLicenses": false,
          "sourceMap": true,
          "namedChunks": true,
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.development.ts"
            }
          ]
        }
      },

但是我们可以添加其他配置,如

test
staging
等。添加配置后,我们可以使用以下配置运行项目:

ng build --configuration=development

这正是我要检测的值(与

isDevMode()
不同),我只是想知道配置
development
production
staging
等是否用于运行应用程序。

如何检测这个值?

angular environment
1个回答
0
投票

这就是我所做的...

// **************************
// environment.interface.ts
// **************************
export type EnvironmentName = 'dev'|'prod'|'test'|'etc';

export interface Environment {
  name: EnvironmentName; // or w/o custom type just use 'dev'|'prod'|'test'|'etc'
}

// **************************
// environment.development.ts
// **************************
import {Environment} from 'environment.interface.ts';

export const environment: Environment = {
  production: false,
  name: 'dev'
};

// **************************
// environment.production.ts
// **************************
import {Environment} from 'environment.interface.ts';

export const environment: Environment = {
  production: true,
  name: 'prod'
};

// **************************
// environment.test.ts
// **************************
import {Environment} from 'environment.interface.ts';

export const environment: Environment = {
  production: false,
  name: 'testing' <-Won't compile because 'testing' is invalid
};

然后在注入环境时使用该接口进行类型安全交互:

import {Environment} from 'environment.interface.ts';

/* snip */
constructor(@Inject('environment') private environment: Environment) {}
/* snip */

我通常将该界面保留在外部角度库中,但它不需要......希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.