angular6根据environments配置文件更改开发所需要的环境的方法

前端开发过程中,我们常常需要根据需求去运行或者打包不同环境的代码,幸运的是,angular给我们提供了environments配置,但是angular6.x的配置方式和angular的其他版本的配置方式是有所不同的,下面我就分别介绍在测试test、预生产pre环境下实现environments配置。

一、angular6.x下environments的配置

首先,在environments文件夹下创建environment.test.ts和environment.pre.ts文件,如下图

然后分别在里面添加如下内容

然后找到angular.json文件,在architect对象下的configurations下添加如下代码:

然后在找到serve,添加如下的代码

可以通过运行ng serve --configuration=test或者ng serve -c test课件在控制台打印:

 {production: false, path: "https://test.webapi.sxmaps.com/"}
    path: "https://test.webapi.sxmaps.com/"
    production: false
  __proto__: Object

同理运行ng serve --configuration=pre或者ng serve -c pre可获取到预生产环境的域名,所以,你只需要在需要用到环境变量的地方引入即可,如

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

二、angular其他版本environments的配置

同样的,首先在environments创建environment.test.ts和environment.pre.ts,然后按照上文的步骤,在里面添加相同的内容,然后去到angular-cli.json文件找到environments,在里面添加如何内容:


然后通过运行ng s --env=test就可以运行测试环境了,在需要的地方引入environment即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。