Skip to content

How to distribute an Electron.js app with WebNN module?

Wanming Lin edited this page Oct 9, 2021 · 2 revisions

This tutorial will guide you to distribute an Electron.js app with integration of webnn-native. After this tutorial, you will be able to experience efficient ML inference by using WebNN API in Node.js.

Build WebNN-native Binding for Node.js

Please follow to this guide to build WebNN-native binding for Node.js, this is a local way to build webnn module before we publish which to https://www.npmjs.com/. Once we publish the WebNN npm package, you can easily use it by a single command, e.g. npm install webnn-*.

This step will generate a build folder, which includes the webnn-native node library.

Create Electron application

Following this official guide to create a simple Electron application.

Integrate WebNN node library to Electron application

  1. Copy build folder generated in section: Build WebNN-native Binding for Node.js to the root directory of your Electron application.

  2. Install bindings module, used for loading webnn native module, via command:

npm install bindings --dev
  1. Load webnn module and redirect WebNN objects via Node's Global variable in preload.js from your Electron application. (Refer to introduction of preload.js in this doc.).
const webnn = require('bindings')(`webnn_node.node`);

global.navigator.ml = webnn.ml;
global.MLContext = webnn.MLContext;
global.MLGraphBuilder = webnn.MLGraphBuilder;
global.MLGraph = webnn.MLGraph;
global.MLOperand = webnn.MLOperand;
  1. Set contextIsolation to false in main.js from your Electron application. See this doc for more information about contextIsolation.

Now you can start writing your application using WebNN API.

Package and distribute your application

Electron provides a couple of ways to package and distribute your application, here we introduces the fastest way, that is Electron Forge.

  1. Add Electron Forge as a development dependency of your app, and use its import command to set up Forge's scaffolding:
npm install --save-dev @electron-forge/cli
npx electron-forge import
  1. Bundles source code with a renamed Electron executable and supporting files into out folder ready for distribution.
npm run package
  1. Create a distributable using Forge's make command:
npm run make

Electron Forge creates the out folder where your package will be located:

// Example for Linux
out/
β”œβ”€β”€ out/make/zip/linux/x64/my-electron-app-linux-x64-1.0.0.zip
β”œβ”€β”€ ...
└── out/my-electron-app-linux-x64/my-electron-app

Following this guide for more configuration of Electron Forge.

Tips: Electron-forge would take a few minutes to check system environment on Windows (while which only take a few seconds on Linux), simply creating an flag file named .skip-forge-system-check in your home directory will skip these checks and shave off your forge start time.