Is it possible to rebuild native modules for Electron without messing with the locally built ones?

I’m building an Electron application that make use of a native module. Currently, I rebuild any native modules in a postinstall-hook after running npm install. This works great.

Unfortunately, this has the side affect that any tests that depend on this module will fail due to it being built for Electron and not my local version of Node. Running npm rebuild solves the problem and tests are passing again but now starting the Electron application fail due to the native module being built for my local Node version instead.

As you can imagine, this becomes pretty tedious. A solution would be to use something like This works but running tests become much slower.

Is there an alternative approach here, that I seem to be missing?

You could run multiple versions of Node and switch between them. You’ll use nvm for Linux and Mac, and nvm-windows for Windows.

I’m not sure how that would solve my problem? Care to elaborate?

The problem as I understand it is that the version of Node installed on your machine is different from the one bundled with Electron. If you run a Node script (a test runner) outside of Electron, you’re using the global Node, which causes issues with the native modules being built for the version inside Electron. If you instead have multiple versions of Node on your computer and use either a version manager or a directory-based virtual environment, you can run the tests using the version that matches what’s in Electron.

Sure, but it seems like building the native dependencies for Electron sometimes cause a mismatch with my local Node version even though the Node version is the same.

For now, I’ve solved it by not calling jest directly but instead running jest via Node bundled with Electron, like so ELECTRON_RUN_AS_NODE=1 electron node_modules/jest/bin/jest.js.

1 Like