How do I load my own native node modules in my Electron app?

2.7k Views Asked by At

I built a C++ native module called foo for my Electron app. The module is located in my project root directory. I added the project to my package.json by setting a local path - a feature that is supported and described here.

  "dependencies": {
    "thumbnail": "file:./foo",

When I execute npm i in my Electron app, all native modules are compiled and my own module spits out a my-electron-app/foo/build/Release/foo.node binary. But "importing" the module inside my Electron app via require("foo") fails and I receive the following error:

vendor.js:40750 Uncaught Error: Could not locate the bindings file. Tried:
 → my-electron-app\build\foo.node
 → my-electron-app\build\Debug\foo.node
 → my-electron-app\build\Release\foo.node
 → my-electron-app\out\Debug\foo.node
 → my-electron-app\Debug\foo.node
 → my-electron-app\out\Release\foo.node
 → my-electron-app\Release\foo.node
 → my-electron-app\build\default\foo.node
 → my-electron-app\compiled\12.13.0\win32\x64\foo.node
 → my-electron-app\addon-build\release\install-root\foo.node
 → my-electron-app\addon-build\debug\install-root\foo.node
 → my-electron-app\addon-build\default\install-root\foo.node
 → my-electron-app\lib\binding\node-v76-win32-x64\foo.node
    at bindings (vendor.js:40750)
    at Object.1YQR (main.js:679)
    at __webpack_require__ (runtime.js:85)
    at Object.Iz1V (main.js:9075)
    at __webpack_require__ (runtime.js:85)
    at Object.4qKS (main.js:2900)
    at __webpack_require__ (runtime.js:85)
    at Object.Sy1n (main.js:12933)
    at __webpack_require__ (runtime.js:85)
    at Object.ZAI4 (main.js:15110)

As you can see, foo.node is not searched in its actual module directory that is my-electron-app/foo/build/Release/.

All other native modules which are located in node_modules/ and which contain a build/Release directory load totally fine.

P.S. If I copy foo.node to one of the expected locations, the module loads fine.

1

There are 1 best solutions below

0
On

May I recommend trying to do it through yarn it will handle many of the dependencies correctly for you and link up any custom stuff.

// add your native module as a dependency to the project. 
// this will hook your custome module to `yarn`/`webpack`/`electron-builder` 

// Now do to tell it build
 `yarn add link:../path/to/native/myModule` 

I have a couple of other options, but I prefer to Keep It Simple KISS :)

Here is another option from SO