I'd like to be able to compile and run a react app directly from VSCode, and then get into debug mode (and do it regardless if it's a javascript or typescript react app).
The expected steps are:
npm start
.How can this be done?
There are two ways to do it:
First way: manualy npm start
, then launch debug mode
First, use VSCode integrated terminal, and run npm start
.
Then, use the following 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"
}
]
}
Hit the "Run" button.
Second way: automate npm start
, then launch debug mode
The following configurations are taken from this blog post.
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
}
}
}
]
}
Note:
In case of a multi-root workspace, where package.json
may be located in a subfolder, add the following to the task definition:
"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)
}
]
}
Hit the "Run" button.
Notes (for both ways):
The first time npm start
will run, it will open a new browser tab\window. You can prevent it by creating a .env
file with the following line:
BROWSER=none
npm start
will run under VSCode's integrated terminal. Accordingly, react's server process will also run under VSCode integrated terminal's process, and it will keep running even after the debug process completes.
Hence, if you want to kill the server process, kill it using the integrated terminal.