[ng]Angular 5 环境信息配置
2018-07-31 本文已影响0人
TT_拓泥
在项目中一个项目对应多个环境是非常常见的,至少你需要面对开发、测试、生产三个环境。
以前我有个很笨的方法,创建一个constant.ts文件,把三个环境的地址写上去,用到哪个把另外两个注释掉。
![](https://img.haomeiwen.com/i9369382/337fee6e3e285c14.png)
这个方法简单,但是很容易出错。万一生产包忘记改地址就会出大问题。
优化一下,在src/environments下已经有两个文件enviroment.ts 和 environments.prod.ts,我们再新增一个environments.stage.ts
![](https://img.haomeiwen.com/i9369382/151b4d6635afc041.png)
三个文件内容也修改一下,增加ServerAddress参数并填写开发、测试、生产所对应的服务地址。
![](https://img.haomeiwen.com/i9369382/0436fd487cdff8ab.png)
![](https://img.haomeiwen.com/i9369382/7c5ea3996db6abcc.png)
![](https://img.haomeiwen.com/i9369382/f4669df280cc5b3c.png)
然后打开angular.json修改配置
![](https://img.haomeiwen.com/i9369382/1e6a9574d10e3308.png)
“production”的配置已经有了,我们复制一份production的配置,将名称改为“stage”,“fileReplacements“-“with”改为刚创建的environment.stage.ts
![](https://img.haomeiwen.com/i9369382/2cafc51f30a56cb4.png)
修改constant.ts的ServerAddress
命令
生产环境
编译:ng build --prod 或 ng build --configuration=production
运行: ng serve --configuration=production
测试环境
编译: ng build --configuration=stage
运行: ng serve--configuration=stage
开发环境
编译:ng build
运行:ng serve