在VS Code中调试Angular 9时切换不同环境文件的方法
在VS Code中调试Angular 9时切换不同环境配置的简便方法
当然有办法啦!我来给你一步步拆解怎么在VS Code的调试模式下快速切换Angular的环境文件,不用每次手动修改代码或者切换命令行参数~
第一步:确认Angular项目的环境配置
首先得确保你的angular.json里已经为每个环境(dev、staging、prod)配置了对应的文件替换规则。如果还没配置,先补全这部分:
打开angular.json,找到你的项目节点下的architect -> build -> configurations,添加或确认以下配置:
"configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], // 保留你原有的prod相关配置(比如压缩、优化等) }, "dev": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.dev.ts" } ] }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ] } }
第二步:给package.json添加环境启动脚本
为了方便调用不同环境的启动命令,在package.json的scripts里新增几个命令:
"scripts": { "start": "ng serve", // 默认localhost环境 "start:dev": "ng serve --configuration=dev", "start:staging": "ng serve --configuration=staging", "start:prod": "ng serve --configuration=production", // 保留你原有的其他脚本(比如build、test等) }
第三步:修改VS Code的launch.json配置
现在把你的launch.json改成支持多环境调试的版本,每个配置对应一个环境,通过preLaunchTask调用对应的npm启动脚本:
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against Localhost", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}", "preLaunchTask": "npm: start" }, { "type": "chrome", "request": "launch", "name": "Launch Chrome against Dev Env", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}", "preLaunchTask": "npm: start:dev" }, { "type": "chrome", "request": "launch", "name": "Launch Chrome against Staging Env", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}", "preLaunchTask": "npm: start:staging" }, { "type": "chrome", "request": "launch", "name": "Launch Chrome against Prod Env", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}", "preLaunchTask": "npm: start:prod" } ] }
怎么用?
配置完之后,打开VS Code的调试面板(快捷键Ctrl+Shift+D),在顶部的调试配置下拉菜单里选择你要调试的环境(比如“Launch Chrome against Dev Env”),按下F5就可以啦!VS Code会先执行对应的ng serve --configuration=xxx命令,加载指定的环境文件,然后自动启动Chrome进行调试。
小提示:如果你的不同环境需要用不同的端口,只要在对应的npm脚本里加上--port xxxx参数就行,比如"start:prod": "ng serve --configuration=production --port 4201",记得同步修改launch.json里的url哦!
内容的提问来源于stack exchange,提问作者doorman
相关产品推荐
相关产品推荐

