You probably don't need nodemon

Tags:
  • JavaScript
  • Nodemon
  • Node.js

What is nodemon?

Nodemon is an npm package that helps you develop Node.js applications by automatically restarting the node application when file changes in the directory are detected. It is a very popular tool among Node.js developers, and it is used in many projects.

Is something wrong with nodemon?

No, there is nothing wrong with nodemon. It is a great tool, and it does its job very well. The thing is, most people don't really need every feature that nodemon provides. They just want to restart their Node.js server when they make changes to their code.

Pure Node.js solution

Since Node.js version v18.11.0, running in 'watch' mode using node --watch restarts the process when an imported file is changed. You can see the changes made in this commit. This new addition means that you can listen to changes you make while developing your Node.js application without the need for nodemon.

It is important to note that when you run node --watch you see the folowing message which indicates that this feature is experimental and might change:

(node:24904) ExperimentalWarning: Watch mode is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

Getting started, the TypeScript way

Since I can't live without TypeScript, I will show you how to use the new --watch flag with TypeScript.

  1. Create a new NPM project in your desired directory:
npm init -y
  1. Create a new TypeScript configuration file in your project directory:
npx tsc --init

This will create a tsconfig.json file in your project directory which you can modify to your needs later on. We don't need to install typescript as a dependency because we are going to use the ts-node loader. You can use other loaders if you prefer but for this example, we are going to use ts-node.

  1. Install ts-node:
npm install ts-node

We are going to use Node.js loaders to be able to run TypeScript files directly. To be more specific, we are going to use the ts-node loader and more specifically the ESM counterpart.

  1. Create a new TypeScript file, for example index.ts:
console.log('Hello, world!');
  1. Run the TypeScript file in watch mode:
node --loader ts-node/esm --watch index.ts

Now, every time you make a change to the index.ts file, the Node.js process will restart automatically. The ts-node project provides you with an executable that you can use to run TypeScript files directly. Those kinds of executables can be found in the node_modules/.bin directory. It is very common among developers to run their apps using the ts-node executable and that's okay, at least for development purposes.

Conclusion

Thanks for reading, I hope you found this article helpful. If you have any questions or suggestions, feel free to reach out to me via email at [email protected].