如何 运行 直接从 VSCode 调试 React 应用程序?

How to run and debug a react app directly from VSCode?

我希望能够直接从 VSCode 编译和 运行 一个 React 应用程序,然后进入调试模式(不管它是否是 javascript或打字稿反应应用程序)。

预期的步骤是:

  1. 运行 npm start.
  2. 在浏览器中启动应用程序。
  3. 进入调试模式。

如何做到这一点?

有两种方法可以做到:

第一种方式:手动npm start,然后启动调试模式

  1. 首先,使用VSCode集成终端,运行npm start.

  2. 然后,使用下面的launch.json:

    {
        "version": "0.2.0",
        "configurations": [ 
            {
                "name": "Chrome",
                "type": "chrome",
                "request": "launch",
                "url": "http://localhost:3000",     // create-react-app's default port 3000
                "webRoot": "${workspaceRoot}/src"
            }
        ]
    }
    
  3. 点击“运行”按钮。

第二种方式:自动化npm start,然后启动调试模式

以下配置取自this blog post.

  1. tasks.json

    {
        "version": "2.0.0",
        "tasks": [
           {
              "type": "npm",
              "script": "start",
              "group": {
                "kind": "test",
                "isDefault": true
              },
              "isBackground": true,   // This prevents the launch.json to wait for the completion of the task
              "problemMatcher": {
                 "owner": "custom",   // This is not needed but, required by the problemMatcher Object
                 "pattern": {
                   "regexp": "^$"     // This is not needed but, required by the problemMatcher Object
                 },
                 "background": {
                   "activeOnStart": true,
                   "beginsPattern": "Compiling...",  // Signals the begin of the Task
                   "endsPattern": "Compiled .*"      // Signals that now the initialization of the task is complete
                 }
              }
           }
        ]
    }
    
  • 注: 如果是多根工作区,其中 package.json 可能位于子文件夹中,请将以下内容添加到任务定义中:

    "options": { 
       "cwd": "${worspaceFolder}/your-subfolder" 
    }
    
  1. launch.json

    {
        "version": "0.2.0",
        "configurations": [ 
            {
                "name": "Chrome",
                "type": "chrome",
                "request": "launch",
                "url": "http://localhost:3000",      // create-react-app's default port 3000
                "webRoot": "${workspaceRoot}/src",
                "preLaunchTask": "npm: start"        // Add prelaunch Task npm: start (defined in tasks.json)
            }
        ]
    }
    
  2. 点击“运行”按钮。

注意事项(双向):

  1. 第一次npm start会运行,会打开一个新的浏览器tab\window。您可以通过使用以下行创建 .env 文件来阻止它:

    BROWSER=none

  2. npm start将在VSCode的集成终端下运行。相应的,react的server进程也会运行在VSCode集成终端的进程下,即使debug进程结束后也会保持运行ning。
    因此,如果您想终止服务器进程,请使用集成终端终止它。