如何直接从VSCode运行和调试React应用程序?
我希望能够直接从 VSCode 编译和运行 react 应用程序,然后进入调试模式(无论它是 javascript 还是 typescript react 应用程序,都可以这样做)。
预期的步骤是:
- 运行
npm start。 - 在浏览器中启动应用程序。
- 进入调试模式。
如何才能做到这一点?
回答
有两种方法可以做到:
第一种方式:手动npm start,然后启动调试模式
-
首先,使用 VSCode 集成终端,运行
npm start. -
然后,使用以下内容
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" } ] } -
点击“运行”按钮。
第二种方式:自动化npm start,然后启动调试模式
以下配置取自这篇博文。
-
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" }
-
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) } ] } -
点击“运行”按钮。
注意事项(两种方式):
-
第一次
npm start运行时,它会打开一个新的浏览器选项卡窗口。您可以通过.env使用以下行创建文件来防止它:BROWSER=none -
npm start将在 VSCode 的集成终端下运行。相应的,react 的 server 进程也会运行在 VSCode 集成终端的进程下,并且在 debug 进程完成后它还会继续运行。
因此,如果您想终止服务器进程,请使用集成终端终止它。