Electron
Electron's main process is Node.js, so it loads the same Node-API addon crossbind builds for Node.js. The window has no Node.js: a preload script exposes the calls it needs, and the main process answers them over IPC.
Setup
Start from the template:
Or, in an existing app, add this config and build the addon:
C++ goes in src/native. The build writes this machine's addons, one per architecture, as dist/my-app.<platform>-<arch>.node, and the loader dist/my-app.native.cjs, which picks one at run time. -p darwin,linux,win32 builds all three desktop platforms.
The addon in the main process
Load the addon in the main process and answer the window over IPC:
The page calls await window.native.sample() and keeps Electron's sandbox. A prebuilt port works the same way: install its -standalone-napi package and import it in the main process, as on Node.js.
Nothing is rebuilt per Electron version: Node-API is ABI-stable, so the same addon loads in Node.js and in Electron, on Windows too, and electron-rebuild is not needed.
Packaging
Keep crossbind's output outside the asar archive: a library's native code reads its data, such as proj.db, with file APIs that cannot open a file inside the archive. With electron-builder:
directories.output moves electron-builder's output out of dist, where crossbind writes, and dist/prebuilt (the static archives the addon was linked from) stays out of the app. Package each platform with its addons in dist; the loader picks the one for the machine.
A -standalone-napi port keeps its data in its own dist/data, so unpack node_modules/@crossbind/** as well. Electron Forge takes packagerConfig.asar.unpackDir: 'dist', and under pnpm it also wants node-linker=hoisted.
Limits
- macOS addons build only on a Mac with Xcode's command line tools. Linux and Windows addons build in Docker on any host, a Mac included.
- One Node environment per process. The addon cannot load again in a
worker_threadsworker of the main process;initNative()there rejects with an error.
examples/desktop-electron is a complete app with electron-builder packaging, and a test that CI runs on macOS, Linux and Windows.