如何在 Visual Studio 代码中调试“create-react-app”?

问题描述 投票:0回答:3

我尝试了这里和其他地方提出的建议,但无法让 vscode 调试器正常工作,即断点永远不会变得活跃🔴,当然它们也不会中断。

应用程序通常使用

npm start
运行,它会调用
react-scripts start

我尝试过这些启动配置:

  {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Launch Chrome against localhost",
        "type": "pwa-chrome",
        "request": "launch",
        "url": "http://localhost:3000",
        "webRoot": "${workspaceFolder}"
      },
      {
        // I adapted this from a config to debug tests
        "name": "create-react-app",
        "type": "node",
        "request": "launch",
        "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
        "args": ["start"],
        "cwd": "${workspaceRoot}",
        "protocol": "inspector",
        "console": "integratedTerminal"
      }
    ]
  }
node.js reactjs visual-studio-code create-react-app react-scripts
3个回答
19
投票

您的first启动配置没问题,您只需要:

  1. 从单独的终端使用
    npm start
    启动开发服务器;
  2. F5
    或 VS Code 中的绿色箭头启动调试器并打开一个新的 浏览器实例。

参考:调试React

.vscode/launch.json

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

更新:编辑答案,用

pwa-chrome
替换已弃用的
chrome


18
投票

这是示例项目反应

npx create-react-app my_app

1 如果还没有,请创建 Launchjson 文件。这会自动创建

  1. 选择网络应用程序(chrome)

3.将端口号8080(默认)更改为3000(或您分配的端口)

4.获取package.json。您可以看到脚本,并且您将注意力集中在启动词上,调试脚本将自动建议单击它。应用程序在端口 localhost:3000 上运行

5.可以用浏览器查看

6.现在在应用程序的开头添加断点(您想要的位置)

  1. 单击启动 chrome

  1. 刷新页面。现在你可以看到断点命中了

它是如何工作的(Gif)点击它以获得更好的质量


0
投票

我有一个稍微改进的方法来执行此操作,当您单击绿色运行箭头时,将启动开发服务器。

  1. tasks.json
    文件夹 (
    docs
    ) 中创建一个 .vscode 文件
  2. 创建一个新任务来启动服务器
{
    "version": "2.0.0",
    "tasks": [
      {
        "label": "Start React App",
        "type": "shell",
        "command": "npm start",
        "options": {
          "cwd": "${workspaceFolder}/apps/client"
        },
        "isBackground": true,
        "problemMatcher": {
          "owner": "custom",
          "pattern": {
            "regexp": ".",
            "file": 1,
            "location": 2,
            "message": 3
          },
          "background": {
            "activeOnStart": true,
            "beginsPattern": "Compiling...",
            "endsPattern": "Compiled successfully"
          }
        }
      }
    ]
  }
  1. 将此任务作为
    preLaunchTask
    添加到
    launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch React App",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}/apps/client",
            "preLaunchTask": "Start React App"
        },
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.