How to rebuild node.js addon when source changes

前端 未结 1 913
孤城傲影
孤城傲影 2021-01-12 15:06

I have a node.js app and I have created a native addon. (In case you need background info, native addons for node.js can be created like this).

In my development en

相关标签:
1条回答
  • 2021-01-12 15:22

    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.

    0 讨论(0)
提交回复
热议问题