serialport in Electron forge (+webpack) renderer fails to load bindings?

836 Views Asked by At

I'm having an issue getting the serialport package to work in Electron Forge + Webpack in the renderer:

Using electron forge CLI, I made a brand new project:

npm init electron-app@latest my-new-app -- --template=webpack

I then installed the latest serialport package:

npm install serialport

I want to use serialport in the renderer so I import it into renderer.js:

import { SerialPort } from "serialport";

Running this however gives me a bunch of import errors:

enter image description here

What I've tried

  • I tried moving this import into the preload.js. This gives a different error about not having a prebuilt version:

Error: No native build was found for platform=win32 arch=x64 runtime=electron abi=110 uv=1 libc=glibc node=16.17.1 electron=22.0.0 webpack=true

  • Tried using electron-rebuild to rebuild serialport electron-rebuild -f -w serialport
  • I tried enabling nodeIntegration: true

This is for an internal development testing tool so security of enabling things that are generally not suggested is okay with me if that is a solution.

1

There are 1 best solutions below

0
Glenn Kroeze On

I was also struggling with a No native build was found for platform error message when importing serialport in Electron's main process. I was using electron-forge to build my distributable. I also tried using electron-rebuild manually, to no avail.

I spent a couple of days digging through Stack Overflow posts and GitHub issues and did some experiments. In the end it looks like the issue is caused by electron-rebuild not detecting serialport's native node modules on certain platforms. In my case, electron-rebuild was rebuilding the serialport native node modules on my M1 MacBook Pro (arm64), but wasn't rebuilding these modules on a Raspberry Pi 4 Model B (armv7l).

What fixed it for me in the end (credit to the this GitHub comment) is running the following commands before Electron's packaging step:

rm --recursive node_modules/@serialport
npm install --no-save --build-from-source [email protected]

This will first delete all the contents of your node_modules/@serialport folder, which contains prebuilt native node modules for several platforms in the bindings-cpp package. Next, we build serialport's native node modules from scratch, so that we (hopefully) end up with a native node module that matches our current platform.

Make sure the version of serialport used in the above command matches the version you depend on!