在调试时,Visual Studio Code不是npm启动我的React JS应用程序

时间:2017-08-20 06:38:47

标签: reactjs visual-studio-code

我想在Visual Studio Code上调试React JS应用程序,所以我按照本教程进行操作:https://code.visualstudio.com/docs/nodejs/reactjs-tutorial

我坚持:

  

确保您的开发服务器正在运行(" npm start")。然后   按F5或绿色箭头启动调试器并打开一个新的   浏览器实例。

正在打开一个新的Chrome实例,要求" http://localhost:3000"但我的应用程序并没有真正运行,似乎只是运行调试器。

如果我手动npm start我的应用程序运行。所以我想launch.json缺少Visual Studio Code用调试器启动应用程序的东西。这就是为什么我坚持确保我的开发服务器运行命令,因为我不知道我在哪里检查这个

这是我的launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceRoot}"
        },
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 9222,
            "webRoot": "${workspaceRoot}"
        }
    ]
}

这是我的package.json:

{
  "name": "tic-tac-toe",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-scripts": "1.0.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

2 个答案:

答案 0 :(得分:1)

我不确定这是否可能。该教程明确指出您应该确保开发服务器已经运行。因此,您必须首先运行npm start并在之后进行调试。

答案 1 :(得分:1)

您可以在 launch.json 中将preLaunchTask设置为自动运行npm start

.vscode 文件夹中创建 tasks.json

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "start",
            "group": {
                "kind": "test",
                "isDefault": true
            },
            "isBackground": true,
            "problemMatcher": {
                "owner": "custom",
                "pattern": {
                    "regexp": "ˆ$"
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "Compiling...",
                    "endsPattern": "Compiled .*"
                }
            }
        }
    ]
}

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Chrome",
      "type": "chrome",
      "preLaunchTask": "npm: start",
      "request": "launch",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}/src",
      "sourceMapPathOverrides": {
        "webpack:///src/*": "${webRoot}/*"
      }
    }
  ]
}

F5 启动调试器,将执行npm start