DEV Community

Meg Meyers
Meg Meyers

Posted on • Edited on

How to Add Nodemon to your TS projects - both CommonJS & ESM

The dev package nodemon has been a great help providing hot-reloading as we code in our JavaScript, json, and other files while developing the in the NodeJS environment. To include the benefits of nodemon in your TypeScript projects so that the unbuilt .ts file hot-reloads as you go takes a bit more configuration, but isn't difficult.

Start by installing nodemon and ts-node as dev tools:

npm i -D nodemon ts-node
Enter fullscreen mode Exit fullscreen mode

In the root of your project (on the same level as your package.json) made a config file called

nodemon.json
Enter fullscreen mode Exit fullscreen mode

The rest of the instructions are split up for CommonJS and ESM.

CommonJS (you do not see "type":"module" in your package.json)
In the nodemon.json file, paste the following code:

{
    "watch": ["src"],
    "ext":  "ts",
    "exec": "ts-node ./src/index.ts"
  }
Enter fullscreen mode Exit fullscreen mode

The extensions I am watching with nodemon are simply the .ts files located in the src folder. The package ts-node will be used to execute the file called index.ts in my src folder. Update per your needs.

Put the following script in your package.json with your other scripts:

"nodemon": "nodemon --watch 'src/**/*.ts' --exec ts-node src/index.ts",

Enter fullscreen mode Exit fullscreen mode

You will now be able to start your project using the following command:

nodemon
Enter fullscreen mode Exit fullscreen mode

and as you code in the index.ts, the hot-reloading will update your server.

ESM ( you do have "type":"module" in your package.json)
Your nodemon.json now looks like this:

{
  "watch": ["src"],
  "ext": "ts",
  "execMap": {
    "ts": "node --no-warnings=ExperimentalWarning --loader ts-node/esm"
  }
}
Enter fullscreen mode Exit fullscreen mode

The package.json script that used to be "nodemon" above now looks like this:

   "dev": "nodemon src/index.ts",
Enter fullscreen mode Exit fullscreen mode

remember "dev" can be anything you want, and please update the actual name of your file if it's not index.

Top comments (0)