我正在使用 nodejs 服务器端 api,使用 dotenv npm 包设置环境变量,并从 package.json 中的 npm 脚本运行代码,如下所示:
"scripts": {
"local": "cross-env NODE_ENV=local nodemon ./bin/www"
}
我需要的是配置我的 .vscode/launch.json 文件。
目前它看起来像:
{
// 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": []
}
请指导我。谢谢,
戈帕尔
最佳答案
您可能希望设置 .dotenv
环境变量如下:
NODE_ENV=local
然后要在您的调试器中要求它,您需要将它添加到您的
launch.json
中。配置如:"runtimeArgs": [
"--require=dotenv/config"
]
这是在上下文中:
{
// 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": [
{
"type": "node",
"request": "launch",
"name": "Launch | local with dotenv config",
"program": "${workspaceFolder}/bin/www/your_script.js",
"runtimeArgs": [
"--require=dotenv/config"
]
}
]
}
--require=dotenv/config
相当于运行 require('dotenv').config()
在您的脚本中或 node -r dotenv/config your_script.js
如果您使用命令行。以下是一些可以在配置中放置环境变量的替代示例。
{
// 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": [
{
"type": "node",
"request": "launch",
"name": "Launch | local using env file",
"program": "${workspaceFolder}/bin/www/your_script.js",
"envFile": "${workspaceFolder}/.env"
},
{
"type": "node",
"request": "launch",
"name": "Launch | local without dotenv",
"program": "${workspaceFolder}/bin/www/your_script.js",
"env" : {
"NODE_ENV" : "local"
}
}
]
}
备注 :此代码尚未经过测试...因此欢迎反馈。
关于node.js - .env 使用 vscode 和 dotenv npm 调试断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54567226/