VSCode: 在启动 Web 项目调试时自动运行 npm 脚本

6

这是我的VS Code launch.json文件:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4321",
            "port": 9222,
            "webRoot": "${workspaceFolder}"
        }
    ]
}

我想要的是在调试开始之前运行npm start命令,即运行开发服务器,然后启动Chrome实例并导航到提供的URL。

因此,我将以下代码片段添加到配置文件中并运行了调试:

            "cwd": "${workspaceRoot}",
            "runtimeExecutable": "npm",
            "runtimeArgs": [
               "start"
            ]

但是我遇到了这个错误:

Attribute runtimeExecutable does not exist ('npm')

有需要帮忙的吗?
2个回答

6

找到解决方案:我需要一个preLaunchTask

launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Chrome against localhost",
            ...
            // This runs dev server before debugger
            "preLaunchTask": "start-dev-server",
        }
    ]
}

tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "start-dev-server",
            "type": "npm",
            "script": "start",
            "isBackground": true,
            "problemMatcher": {
                "owner": "npm",
                "background": {
                    "activeOnStart": true,
                     "beginsPattern": ".*",
                     "endsPattern": "Finished.+"
                },
                "pattern": {
                    "regexp": "",
                }
            }
        },
    ]
}

4
我使用了这个,但它没有完成,因此它不会返回并启动Chrome窗口。 - Dani Pralea

0

这是对我有效的方法:

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "dev",
            "problemMatcher": [],
            "label": "npm: dev",
            "detail": "vite --port 4000"
        }
    ]
}

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch via Chrome",
            "url": "http://localhost:4000",
            "webRoot": "${workspaceFolder}",
            "preLaunchTask": "npm: dev", 
        }
    ]
}

然后只需按F5或单击“开始调试”按钮。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接