问题
使用VS Code调试golang时需要预先加载一个.env的环境变量文件, 怎样配置VS Code 才能加载这个文件?
如下图示,项目中有个环境变量的配置文件, 在调试时需要先将它加载出来

在代码里需要用到这些环境变量

解决方法
修改launch.json配置文件, 在配置文件中设置envFile属性. 如下所示.
点击
Run and Debug按钮点击小齿轮按钮,打开
launch.json配置文件修改
envFile属性, 设置为"envFile": "${workspaceFolder}/.env"如下图示

下面为参考配置
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
// "mode": "auto",
"mode": "debug",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}",
"envFile": "${workspaceFolder}/.env",
// "showGlobalVariables": true
}
]
}可以参考官方文档

注意事项
环境变量文件.env 不可以写成下面这个样子,也就是不能添加export 只能是键值对的形式出现

评论区