How to execute a command every time an Nx project changes
Recently, I was working on a CLI tool to display dependency information from the Nx project graph.
The tool proved to be valuable, but would even be more valuable if the information would update every time a file changed in one of the Nx projects. That would enable fellow engineers to analyze the information live during development and see if their changes impacted the dependency graph.
So it was time to add a watch option.
While looking into Node.js' watch function and third-party libraries, I stumbled upon Nx's built-in watch command. 🤩
It turns out that Nx already provides us with a powerful command to execute a command when changes are detected in one or more projects.
Here is how it works:
npx nx watch --projects=<project-to-watch> -- <command-to-run>
So, to log a line when a file in the my-app
project changes, you can run:
npx nx watch --projects=my-app -- echo "Change detected!"
To watch changes in multiple projects, you can use a comma-separated list:
npx nx watch --projects=my-app,my-lib -- echo "Change detected!"
Finally, to execute a command when any project changes, you can use --all
:
npx nx watch --all -- echo "Change detected!"
So, if you wish to run a Node.js script any time a file in any project changes, you can run:
npx nx watch --all -- node your-script.js
How convenient is that! 🚀🚀
The full documentation is available right here.
Thank you, Nx, for this great tool! 🙏 🙇♂️
Happy watching! ⚡️