- Building Enterprise JavaScript Applications
- Daniel Li
- 237字
- 2021-07-23 16:31:14
Automating development using nodemon
At the moment, to see the final product, we have to run the build script after each time we modify our source code. While this is fine, it can be annoying and a time-waster. nodemon is a tool that monitors for changes in our code and automatically restarts the node process when a change is detected. This can speed up development and testing, as we no longer need to run the build and serve scripts manually. Furthermore, the API served from our machine will always be the most up-to-date version.
First, let's install nodemon:
$ yarn add nodemon --dev
Next, add a watch script that uses nodemon instead of node:
"scripts": {
"build": "rimraf dist && babel src -d dist",
"serve": "yarn run build && node dist/index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "nodemon -w src --exec yarn run serve"
},
This command instructs nodemon to watch for file changes in the src directory and, whenever one is detected, to execute yarn run serve and restart our server.
Now, run yarn run watch, and make a small file change in src/index.js (for example, change the text returned in the response). Pay attention to the console and you'll see nodemon detecting changes and restarting our server:
[nodemon] restarting due to changes...
[nodemon] starting `yarn run serve`