[Express.js] Setting Up Hot Reloading with Nodemon
Express.js Series Articles
- Setting Up an Express.js API with TypeScript from Scratch
- Setting Up Coding Conventions and Transpiling TypeScript into JavaScript
- Adding Debug Configuration and Starting the Debugger with VSCode
- (current)Setting Up Hot Reloading with Nodemon
- (To be updated)
Preface
I am building an API template using Express.js and TypeScript to streamline future development projects. This article is part of a series documenting my progress, helping me deepen my understanding. Your feedback and suggestions are welcome.
Adding hot reloading can make development more convenient by eliminating the need to manually rebuild when files change. This article will introduce how to set up hot reloading.
Step 1: Install Nodemon
Install Nodemon as a development dependency.
% npm i -D nodemon
- Ref: nodemon
Step2: Add nodemon.json
Create a nodemon.json
file with the following content. You can adjust these settings according to your needs.
{
"watch": ["src"],
"ext": "ts",
"exec": "npx ts-node ./src/app.ts"
}
Step3: Start the Server with Nodemon
You can start the server using the Nodemon command.
% npx nodemon
npx nodemon
[nodemon] 3.1.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `npx ts-node ./src/app.ts`
Example app listening on port 3000
If you prefer not to create a nodemon.json
file, you can start the server with the following command.
% npx nodemon --watch "src/**" --ext "ts" --exec "npx ts-node ./src/app.ts"
x ts-node ./src/app.ts"
[nodemon] 3.1.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**
[nodemon] watching extensions: ts
[nodemon] starting `npx ts-node ./src/app.ts`
Example app listening on port 3000
Step 4: Confirm the Server is Running
Navigate to http://localhost:3000/
in your browser. You should see “Hello World!” displayed on the screen.
Step 5: Modify a File
Change app.ts
as shown below and save the file.
// ......
app.get('/', (req, res) => {
res.send('Hello World 2024!')
})
// .....
After saving the file, the terminal will display messages like this.
[nodemon] restarting due to changes...
[nodemon] starting `npx ts-node ./src/app.ts`
Example app listening on port 3000
Step 6: Confirm the Changes
Navigate to http://localhost:3000
again, and it should now display “Hello World 2024!”.
Conclusion
Now, your server will automatically restart whenever you make changes, saving you the time of manually rebuilding. In future articles, we will add controllers and services and set up relative paths.
You can find the source code at the link below.
https://github.com/FlyRayTsou/expressjs-api-template/tree/v0.0.4
Reference
- Using ChatGPT to refine the article makes it more natural.
- How to watch and reload ts-node when TypeScript files change