Configuring nodemon with TypeScript (2023)

Originally posted onblog to LogRocket.

nodemonis a CLI for Node.js that makes JavaScript development much faster by restarting a running process when a file is updated. For example, if you have a project with aindex.jsfile you want to quickly test and iterate on, you can runnodemon index.js, and a new Node.js run process will start toindex.js, restarting whenever a file in the project is updated. Simple, right?

Well, the simplicity offered by nodemon diminishes as you introduce TypeScript into your project and as your project's complexity increases. But fear not! In this article, we'll review three nodemon configuration methods, each offering different features and functionality that can meet the needs of your TypeScript project.

We will also review three nodemon alternatives with extra features and more customization if you are looking for nodemon alternatives that better suit your project requirements. Since each option has its own pros and cons, we'll discuss whether or not each option will meet our project's needs, and if not, which option is the best choice.

Method 1: Workflow without configuration

As of v1.19.0,nodemon has built-in support for Typescript fileswith the help ofit tsthat does not require manual configuration. By default, nodemon uses theItCLI as a runtime program to run JavaScript files; for TypeScript files, nodemon usesit tsas the running program.

it tsis a TypeScript execution engine that compiles and executes TypeScript files.it tsserves as a substitute for theItCLI then the same arguments can be passed to theit tsCLI like theItCLI.

This method requires a nodemon version ≥1.19.0 to be installed. Furthermore,it tsmust be installed in your project. Since these two packages will likely only be used during development, they should be installed asDevDependências.

addition of wires--devnodemon ts-node

Once these two dependencies are installed, you can pass a TypeScript file to nodemon as you would a JavaScript file.

npx nodemon ./main.ts

Advantages and disadvantages

This method is by far the simplest as it requires minimal setup. It is built into nodemon itself, so all that is needed is to install the necessary packages.

However, this method falls short in terms of flexibility and customization. Many projects require more than just the patterntscTypeScript compiler used byit ts, and still others will require more advanced configuration; if this scenario describes your needs, proceed to method two.

Method 2: manual configuration

The built-in nodemon's TypeScript executor provides a method to get up and running with minimal configuration:manual configuration.

If your project requires more flexibility in how your files are executed, nodemon allows users to create a configuration file to meet a project's exact specifications. By using a custom configuration file, you can get the most benefit from nodemon's flexibility and take advantage of all the settings it offers.

The specific configuration we are going to configure isexecutive map, or execution map. This setting tells nodemon which executables or commands to run for different file types. For now, let's look at how to set up an execution map specifically for TypeScript files.

To create a configuration file, create a new file in your project's root directory callednodemon.json.

Nonodemon.jsonfile, create a new JSON object with aexecutive mapproperty. the value ofexecutive mapproperty must be an object.

{ "execMap": {}}

Withinexecutive mapobject, create a new property fortsfiles. The value of this property should be whatever command you want to run when running your TypeScript files. For example, you can set it toit ts, or any other script or run command.

{ "execMap": { "ts": "it ts" }}

Voilà, nodemon is now configured to run a custom command for TypeScript files. When you call nodemon with a TypeScript file (i.e.nodemon index.ts), nodemon will find the command in theexecutive mapthat correlates with.tsfiles and then run that command, passing the file as the final argument (i.e.ts-node index.ts).

Bonus tip:if you want to pass the file path elsewhere in the command (i.e. not as the final argument), type{{pwd}}where the file path should be placed in the command. For example, if yourexecutive mapcommand to.jsfiles isnode {{pwd}} && echo "Hello world"then callingnodemon index.jswill runnode index.js && echo "Hello world".

Advantages and disadvantages

Using a custom nodemon configuration file opens up a lot of flexibility required by many projects. There are many settings you can configure as explained bythe nodemon documentation.

Accordingly, this method should only be used in cases where the first method will not meet your project requirements. If your project just needs its TypeScript files to compile and run, then the built-in nodemon supports TypeScript withit ts(method one) will probably be the best option for your project.

If your project needs even more customization, consider method three.

Method 3: custom run command

nodemon shines as a tool to help run and restart the execution of a single file when any file in a project is updated. However, not all projects have a single entry point; that is, many modern projects require the use of an external tool to initialize or run your project.

Whereas methods one and two offer ways to run a single file, this method will offera way to run a single command, thus offering the greatest flexibility of these methods.

Back thenpackage.jsonfile, create ato startroad map. This will serve as the command that will be executed and restarted by nodemon when a file is changed.

To run this command with nodemon, run:

nodemon--exec "thread start"# ornodemon--exec "npm run start"

That passes theto startscript as the executable command to be run in your project by nodemon.

Bonus tip:you can do full nodemon command (i.e.nodemon --exec "beginning of thread") adeveloperscript, so that callingyarn developerwill run nodemon with your custom run command.

Advantages and disadvantages

While this method offers the most flexibility in terms of what can be executed, it defeats nodemon's most notable feature: (re)executing a single file execution when a file in the project is updated.

Before choosing this method, consider whether methods one or two are better suited to your project needs.

What are some alternatives to nodemon?

nodemon is certainly a powerful tool for rapid development with Node.js. However, there are also numerous alternatives that may be better suited for your project.

In the next part of this post, we will consider three alternatives to nodemon:ts-node-dev,pm2and a DIY file watcherbuilt with installment.

Alternativa 1: ts-node-dev

In the first method, we discussed how nodemon usesit tsto compile and run TypeScript files.[ts-node-dev](https://github.com/wclr/ts-node-dev)combines the file watching capabilities of nodemon with TypeScript support fromit tsinto a nodemon-like service that is specifically tailored to TypeScript.

ts-node-devinteracts directly with the TypeScript execution engine and compilation process to provide a more efficient system than nodemon for TypeScript files.ts-node-devit only reloads when changes are made to files that are a dependency (that is, imported by) the input file. Additionally,ts-node-devshares a unique build process between reboots to maximize efficiency and make reboots faster.

To usets-node-dev, first install it as adevDependency:

addition of wires--devts-node-dev

Then to run your file and restart on file changes run:

ts-node-dev--reappearanceindex.ts# ortsnd--reappearanceindex.ts

To replaceindex.tswith the input file for your project.

Advantages and disadvantages

ts-node-devis a great choice for rapid TypeScript development because it is more efficient than nodemon and is made specifically for TypeScript.

However, while it offers some level of configuration,ts-node-devis arguably much less customizable than nodemon. It also doesn't restart on changes to static assets, which can be helpful when serving images to a web server. Make sure you consider these drawbacks before choosing.ts-node-devfor your project.

Alternative 2:pm2

[pm2](https://github.com/Unitech/pm2)is a battle-tested and production-ready process manager for Node.js programs that is loaded with tons of features and configuration options. It is used to manage multiple Node.js applications and processes and comes with a load balancer to manage heavy applications with large amounts of queries.

pm2supports hot reloading, application monitoring and detailed process management. In addition to all these features,pm2offers automatic restart functionality that will restart your program when a file is changed.

to start withpm2, install it globally on your system.

npminstallpm2-g

Next, we'll have to do a bit of configuration. Create a file calledecosistema.config.jsonand enter the following content:

module.export = { apps: [ { name: "TSServer", road map: "it ts", arguments: "index.ts", // replace this with your project's input file } ]}

This will create a new application called "TSServer" that will runts-node index.ts. Finally, run:

pm2 start ecosystem.config.js--justTSServer--to attend

This will run the TSServer application and restart on file changes with theto attendargument. A fancy table with information about your application should be printed to the terminal and a column titledAttendingMust ReadAblefor your application. This app will now run in the background until you callpm2 stop TSServer.

Advantages and disadvantages

As stated earlier,pm2is packed with exciting features that are incredibly useful for large production applications. However, for this reason,pm2may well be overkill for your project.

If you are just looking for a simple way to restart TypeScript projects, this method will probably not be the best choice for your project and you should consider other alternatives or nodemon.

Alternative 3: DIY file watcher with Parcel

Sometimes the best way to make something is to do it entirely yourself from scratch.

As we've seen with all of the previous methods and alternatives, there is always a potential downside or downside to using one option over another. You can avoid these limitations by building a file watcher from scratch and even learn something along the way!

For this DIY file watcher, we'll take advantage of the features provided by the Parcel file wrapper, which can be used to develop web apps or Node.js libraries.

Parcel exposes a JavaScript API to watch for events in the packaging process. Each time a file is updated, the packaging process for our TypeScript project is restarted. When the wrapping process is complete, we will spawn a child process that executes the wrapped and compiled JavaScript file.
Here is an example ofmy DIY file watcher built with Parcel:

// make sure you have @parcel/core and @parcel/config-default// installed as devDependenciesmatter {Portion} of '@package/core';matter {to generate, ChildProcessWithoutNullStreams} of 'child_process';to leave packer = novo Portion({ Appetizer: 'src/index.ts', defaultConfig: '@parcel/config-default', defaultTargetOptions: { distDir: `${process.cwd()}/dist` },});asynchronous function principal() { to leave cp: ChildProcessWithoutNullStreams; await packer.to attend(() => { cp?.matar() cp = to generate("It",[`${process.cwd()}/dist/index.js`]) cp.stderr.about('data', (data) => { console.record(`stderr:${data}`); }) cp.stdout.about('data', (data) => { console.record(`stdout:${data}`); }); });}principal()

Another benefit of this method is that you can actually write your entire file watcher in TypeScript! To run your file watcher just run your file withit ts.

ts-node runner.ts

Advantages and disadvantages

This method by far offers the most customization capability, as you are designing the file observation process yourself. You can spawn a different child process if needed, or spawn multiple ones, and you can run any other JavaScript/TypeScript code as needed when a file is updated.

However, as this is a DIY solution, it is your responsibility to maintain and maintain the executor, while this is done for you by experienced open source developer teams for all other options provided in this article. As long as you know what you're doing, however, this alternative option is certainly not to be overlooked!

Conclusion

There are numerous ways nodemon can be configured to meet your project's needs and requirements. However, if none of these methods work for you, there are also ample alternatives that can offer different advantages over nodemon for your project. I hope you found a method in this article that fits your specific use case.

Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated: 04/30/2023

Views: 6184

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.