Set up Hot Reload for Typescript ESM projects

mangadev

Wagner Manganelli (aka manga)

Posted on August 25, 2023

Set up Hot Reload for Typescript ESM projects

TL;DR

Are you moving your projects to use ES Modules but you are facing some unexpected issues? You are not alone in this fight. In this tutorial, you will learn how to set up nodemon along with ts-node.

Wait, why are we not using ts-node-dev? Currently, there are some issues related to TS ESM projects that are making its use harder. Check this issue for more details.


Hot-Reload?

This technique is handy when you are developing locally. This will automatically watch changes over your source code and updates for you. So, you just have to make your code work and the hot-reloading will do the magic from behind the scenes. This will improve your code development process bringing more efficiency and velocity, as you will not have to restart every time your application.


Let's set it up 🔧


Prerequisites

  • Node.js >= v18.12.0

Initial steps

mkdir app-esm-hot-reload
cd app-esm-hot-reload
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install dev dependencies

npm install --save-dev typescript@5.1.6 ts-node@10.9.1 nodemon@3.0.1
Enter fullscreen mode Exit fullscreen mode

Initialize TypeScript

  npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Configuration steps

  • package.json
{
  ...
  "type": "module",
  "scripts": {
    "build": "tsc",
    "dev": "nodemon src/index.ts",
    "start": "node dist/index.js"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode
  • tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true
  },
  "ts-node": {
    "esm": true
  },
  "exclude": ["node_modules", "./*.ts", "__test__"]
}
Enter fullscreen mode Exit fullscreen mode
  • Create index.ts
mkdir src
touch src/index.ts
Enter fullscreen mode Exit fullscreen mode
  • Execute script
npm run dev
Enter fullscreen mode Exit fullscreen mode
  • Make changes to the index.ts or any other file

Your app should be reloaded automatically

  • That's it! Now you can start coding without bothering with restarting your application at every change. 🍺
P.S. you can refer to this template.

Useful links


Tutorials that might interest you as well


I hope this tutorial improves your development process.

Thank you for reading! Happy coding! 🥳

💖 💪 🙅 🚩
mangadev
Wagner Manganelli (aka manga)

Posted on August 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related