具有不同“配置文件”的Angular ng构建

Joh*_*onn 4 angular-cli angular

在Maven(Java)中,有可能构建具有不同“配置文件”的Webapp War,例如,“配置文件”指示要放入配置文件的Web服务的URL。因此,“测试配置文件”将指示与“生产配置文件”不同的URL。

是否有类似于ng build的配置文件?

Abd*_*heb 9

对于Angular 6+

为文件environments夹内的每个配置文件创建一个文件:

environments/environment.ts
environments/environment.prod1.ts
environments/environment.prod2.ts
Run Code Online (Sandbox Code Playgroud)

并且inisde每个文件都放了对应profile的参数:

export const environment = {
  production: true,
  serverUrl: "http://prod1.site.com"
};
Run Code Online (Sandbox Code Playgroud)

您可以像这样访问组件/服务中的参数:

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

@Injectable()
export class SomeService {
  SERVER_URL: string = environment.serverUrl;
Run Code Online (Sandbox Code Playgroud)

并在angular.json下面添加新的配置文件环境configurations

"configurations": {
  "prod1": { ... },
  "prod2": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod1.ts"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

最后在构建应用程序时选择配置文件:

ng build --configuration = prod1
Run Code Online (Sandbox Code Playgroud)


Ric*_*ick 5

在使用angular-cli创建的每个项目中,都有一个environment.ts和environment.production.ts文件,该文件导出具有布尔类型的属性称为production的对象。

在第一个文件中将其设置为false,在生产文件中将其设置为true。

默认情况下,在调用ng build时,angular-cli使用第一个文件。

如果要使用生产文件,则必须调用ng build --env = prod。

在config.ts文件中使用它

在config.ts文件中,您可以询问环境文件导出的布尔值的状态。

例如:

import { environment } from 'environments/environment';

export class Config {
    public static get webApiUrl() {
        if (environment.production) {
            return 'https://testapi.be';
        }
        return 'http://localhost:60000';
    }
}
Run Code Online (Sandbox Code Playgroud)

创建自己的环境

您可以通过将其命名为environment.your_environment.ts来创建自己的环境文件。

然后,您必须添加一个布尔属性your_environment,并将其添加到所有其他文件中,并且仅在文件中将其设置为true。

之后,您必须将其添加到以下环境部分的angular-cli.json文件中:“ your_environment”:“ environments / environment.your_environment.ts”。

通过ng build --env = your_environment,您可以使用该文件。

import { environment } from 'environments/environment';

export class Config {
    public static get webApiUrl() {
        if (environment.production) {
            return 'https://productionapi.be';
        }
        if (environment.your_environment) {
            return 'https://testapi.be';
        }
        return 'http://localhost:60000';
    }
}
Run Code Online (Sandbox Code Playgroud)