launch.json
FileExpress.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web applications and APIs. It simplifies the process of handling HTTP requests, routing, and middleware.
TypeScript is a superset of JavaScript that adds static typing to the language. It helps catch errors early in the development process and makes the code more maintainable and scalable, especially in larger projects.
Debugging is crucial for identifying and fixing bugs in the code. It helps developers understand how the code behaves, find logical errors, and ensure that the application functions as expected. Without proper debugging, it can be extremely difficult to track down and resolve issues.
VSCode is a popular code editor with powerful debugging capabilities. It provides an integrated debugger that allows developers to step through the code, set breakpoints, inspect variables, and analyze the call stack. This makes the debugging process more efficient and user - friendly.
First, create a new directory for your project and navigate to it in the terminal:
mkdir express-typescript-debug
cd express-typescript-debug
Initialize a new npm project:
npm init -y
Install the necessary dependencies:
npm install express
npm install --save-dev typescript @types/node @types/express ts-node-dev
Create a tsconfig.json
file:
npx tsc --init
You can modify the tsconfig.json
file to suit your project needs. For example:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Create a src
directory and an app.ts
file inside it:
mkdir src
touch src/app.ts
Add the following code to src/app.ts
:
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
launch.json
FileIn VSCode, open the command palette (Ctrl + Shift + P
or Cmd + Shift + P
on Mac) and search for Debug: Open launch.json
. Select Node.js
as the environment. Replace the content of the launch.json
file with the following:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Express.js with TypeScript",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"dev"
],
"port": 9229,
"skipFiles": [
"<node_internals>/**"
]
}
]
}
Add a dev
script to your package.json
file:
{
"scripts": {
"dev": "ts-node-dev --inspect src/app.ts"
}
}
Press F5
or click on the green play button in the Debug sidebar in VSCode. The application will start in debug mode, and you can now start debugging.
To set a breakpoint, click on the left margin next to the line of code where you want to pause the execution. When the debugger reaches that line, the execution will pause, and you can inspect the state of the application.
When the execution is paused at a breakpoint, you can hover over variables to see their values. You can also use the Variables
panel in the Debug sidebar to view and inspect variables.
Express.js middleware functions are executed in the order they are defined. To debug middleware, set breakpoints inside the middleware functions. You can then inspect the req
and res
objects to understand how the request is being processed.
import express from 'express';
const app = express();
const port = 3000;
const loggerMiddleware = (req, res, next) => {
console.log(`Received ${req.method} request to ${req.url}`);
next();
};
app.use(loggerMiddleware);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
When an error occurs during debugging, VSCode will stop at the line where the error was thrown. You can use the call stack in the Debug sidebar to trace back the sequence of function calls that led to the error.
Asynchronous code in JavaScript and TypeScript can be challenging to debug. VSCode allows you to set breakpoints inside asynchronous functions and promises. You can also use the Debug Console
to log the state of the application at different points in the asynchronous flow.
Keep your launch.json
file organized and remove any unnecessary configurations. This makes it easier to manage and understand the debugging settings.
Logging can be a useful tool in addition to debugging. You can use console.log
statements to output information about the state of the application at different points. This can help you quickly identify issues and understand the flow of the code.
Before starting the debugging process, make sure to run your tests. Unit tests and integration tests can help catch many issues early, reducing the amount of time spent on debugging.
Debugging Express.js applications written in TypeScript in VSCode is a powerful and efficient way to identify and fix issues in your code. By understanding the fundamental concepts, following the usage methods, and applying common and best practices, you can streamline the debugging process and improve the quality of your applications. With the integrated debugger in VSCode, you have all the tools you need to debug your Express.js TypeScript applications effectively.