Dockerfile npm build fails with wrong node_module_version errors, same process in command line works

I’m having a strange issue with my project. I’m getting the

The module xxx was compiled against a different Node.js version using NODE_MODULE_VERSION xx. This version of Node.js requires NODE_MODULE_VERSION yy

Error when deploying the project. Fwiw, it’s related to onoff library (or epoll), i.e

const Gpio = require('onoff').Gpio();

throws the error. If I ssh to the main process and run

npm install onoff
cd node_modules/onoff
npm install

const Gpio = require('onoff').Gpio();
> undefined

I can get rid of the error, but I can’t figure out what is going on with my Dockerfile and why I can’t get it working. (a part of) my dockerfile (it’s loosely based on balena-electronjs -template)

# I've tried with different versions of node 10.x and 12.x
FROM balenalib/raspberrypi3-debian-node:12.13-buster-build as build

# … some other install packages here (related to Electron)

# I had to install these separately to get some things working, but can't remember why... ;)
RUN JOBS=MAX npm install -g node-gyp
RUN JOBS=MAX npm install node-hid --build-from-source

RUN JOBS=MAX npm install \
 --production --unsafe-perm \
  && npm cache clean --force \
  && rm -rf /tmp/* \
  && node_modules/.bin/electron-rebuild

# Move app to filesystem
COPY ./app ./

# create-react-app build
RUN JOBS=MAX npm run build

my package.json has

"electron": "^8.5.5", // I've tried with Electron 1.7, .... 9, 10, ... as well
"electron-rebuild": "^2.3.5",
"onoff": "^6.0.1",

I’ve also tried adding

RUN JOBS=MAX npm install onoff
RUN cd ./node_modules/onoff && npm run install

to my Dockerfile, but this didn’t get rid of the error (even though running these in command line worked).

Am I missing something obvious here?

Native modules must be compiled for the correct target runtime (node or electron) and version.
When you npm install --build-from-source a native module, it gets compiled for the node version you are using to run npm.
If you want these to be built for electron, you’ll need to either:

I was able to fix this issue by re-creating the image from scratch and adding new things one or two at a time. Can’t tell what was the issue since I had been running electron-rebuild for each new module in the first place. Really strange, but now this is working again.