How to rebuild node.js addon when source changes

六月ゝ 毕业季﹏ 提交于 2019-12-05 10:08:19

I solved this by having nodemon use the -x option to run npm. Then the npm script can execute the build and run scripts sequentially.

Here's the relevant part of my package.json:

"scripts": {
  "dev": "nodemon -x \"npm run buildrun\"",
  "buildrun": "npm run build && npm run server",
  "build": "echo Building Addon && cd addon && node-gyp build",
  "server": "nodemon server.js",
}

You kickstart this by running npm run dev.

dev runs nodemon with the -x option and the command is npm run buildrun. Then nodemon restarts the npm buildrun script every time code changes. This was the main part I had trouble figuring out.

To explain the rest, the buildrun script runs two scripts back to back. The first one (build) builds the addon and the second one (server) runs the server.

The server script actually runs nodemon as well: it runs another nodemon to run the server script with nodemon server.js.

Technically, by having npm calling nodemon again (with the right configuration files, different arguments and context) nodemon could watch a different piece of the codebase and restart a different part of the system (e.g., watch just the server code without rebuilding the whole addon, which is what my actual code does.)

By calling nodemon with the -x option and having the entire build-and-run script get restarted when code changes, I was able to sequence the actions to get nodemon to first build the addon, wait for the build to complete, and then run the server.

This nodemon -x \"npm ...\" technique wasn't obvious to me at first and it actually took me half a year to come up with this solution. So, I'm sharing this because other people may find this technique useful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!