6

我正在使用 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": []
}

请指导我。谢谢, Gopal.R

4

2 回答 2

10

您可能希望.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"
            }
        }
    ]
}

注意:此代码尚未经过测试...欢迎提供反馈。

于 2019-09-27T02:43:18.270 回答
1

我对打字稿调试有同样的问题,我在这里找到了答案。需要指定runtimeArgsenvFile参数才能使其工作。

TypeScript调试示例launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}/src/server.ts",
            "preLaunchTask": "tsc: build - tsconfig.json",
            "outFiles": [
                "${workspaceFolder}/built/**/*.js"
            ],
            "runtimeArgs": [
                "--require=dotenv/config"
            ],
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}
于 2021-02-01T15:33:33.053 回答