- Building Enterprise JavaScript Applications
- Daniel Li
- 403字
- 2021-07-23 16:31:21
Using the Visual Studio Code debugger
Open up src/index.js on VSCode. If you hover your mouse to the left of the line numbers, you'll see some small, dimmed, red circles appear; you can click on the circle to insert a breakpoint on that line. This means whenever the script is executing and reaches that line, it will pause there. This allows us to examine the variables available within scope at that point. Go ahead and set the breakpoint at line 5.
const requestHandler = function (req, res) {
debugger;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
}
After you've set the breakpoint, go to the Debugger tab in your editor. Click the Start Debugging button (usually this looks like the "Play" button: ?); this will execute the current file:
The debugger throws an error because it doesn't recognize the ES6 modules' import syntax. This is because we are running the debugger on the source file directly, instead of the compiled file produced by Babel. To instruct VSCode to process modules, we can do one of two things:
- Install the @babel/node package and instruct VSCode to execute our file using babel-node.
- Instruct VSCode to add the --experimental-modules flag when running Node. This has been supported since Node v8.5.0.
To do either of these, we need to add configurations to the VSCode debugger. Configurations in VSCode are defined as JSON objects inside a launch.json file. To edit the launch.json file, click the cogwheel button () near the top. Then, paste in the following JSON object, which will provide us with both configurations mentioned before, as well as an option to run the program as normal:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Node",
"program": "${file}",
"protocol": "inspector"
},
{
"name": "Babel Node",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-
node",
"runtimeArgs": [
"--presets",
"@babel/env"
],
"program": "${file}",
"protocol": "inspector"
},
{
"name": "Node with Experimental Modules",
"type": "node",
"request": "launch",
"runtimeExecutable": "~/.nvm/versions/node/v8.11.4/bin/node",
"runtimeArgs": [
"--experimental-modules"
],
"program": "${file}",
"protocol": "inspector"
}
],
"compounds": []
}
Now, also remember to install the @babel/node package as a development dependency:
$ yarn add @babel/node --dev