node.jswebpackelectronelectron-buildernative-module

Building native modules as part of electron app


I am currently working on building out an application using electron, react, typescript, and NodeJS native modules. I started the application using the provided boilerplate code (https://github.com/electron-react-boilerplate/electron-react-boilerplate).

I am looking to add some native modules to the application, preferably written as a library within the application. Currently I have written a C++ module to read some memory stats. I can get the module working when running in development mode by importing the module as follows: const native = require('./lib/memmonitor/build/Release/memmonitor.node');'.

The first issue I am running into is the module requires to be manually built by going into the director and manually running electron-rebuild. Ideally this should be triggered by running yarn install or yarn electron-rebuild (both defined in the boilerplate package.json); however the commands only seem to care about the native modules which have been included via node_modules.

The second issue I am having is that when packaging the application the node modules do not get included into the final build, resulting in the electron app failing to start due to not finding the node module.

Is it possible to build a native module as part of the application build, and include it in the final package, or is it standard to have a separate repo for each custom native module, have the application include the library as a dependency?


Solution

  • So after a couple weeks on and off trying to figure out how to get this work, it turns out the answer was a oneliner using yarn.

    The "trick" was to use yarn add link:../path/to/native/module to add the module as a dependency to the project. This in turn you tell yarn/webpack/electron-builder about the module, and the tools will correctly handle building the module.