Build Electron Main/Preload ESM

1.0.5 · active · verified Sun Apr 19

build-electron is a specialized command-line tool designed to simplify the use of ES Modules (ESM) in Electron's main and preload processes. It targets the persistent challenge of Electron's lack of native ESM support by providing a pre-configured Webpack 5 build system, abstracting away complex configurations. It is currently at version 1.0.5 and appears to have an infrequent release cadence, with minor fixes and updates being pushed when needed. Its key differentiator is its focus solely on the Electron main/preload code, intentionally avoiding renderer code to keep the tool simple and framework-agnostic. This allows developers to pair it with existing frontend build tools like Create React App without conflict, aiming for a plug-and-play experience until Electron natively supports ESM. It is not a boilerplate but a build utility.

Common errors

Warnings

Install

Quickstart

This quickstart demonstrates how to set up `build-electron` for developing and building an Electron application using ES Modules for the main and preload processes, including a basic Electron main entry file and `package.json` scripts.

yarn add -D build-electron concurrently wait-on electron electron-builder

// build-electron.config.js
module.exports = {
  mainEntry: 'src/main/index.js',
  preloadEntry: 'src/preload/index.js',
  outDir: 'build',
  mainTarget: 'electron27.0-main', // Adjust target Electron version as needed
  preloadTarget: 'electron27.0-preload',
};

// package.json (add to scripts and config)
{
  "main": "build/main.js",
  "build": {
    "files": [
      "build/**/*"
    ]
  },
  "scripts": {
    "start": "concurrently -k \"build-electron -d\" \"wait-on build/.build-electron-done && electron .\"",
    "build": "build-electron"
  }
}

// src/main/index.js (example Electron main process entry)
import { app, BrowserWindow } from 'electron';

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: require.resolve('../build/preload.js') // Ensure correct path to built preload
    }
  });
  win.loadFile('index.html'); // Or load a URL
}

app.whenReady().then(() => {
  createWindow();
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// To run:
npm run start

// To build for production (e.g., for macOS):
npm run build && npx electron-builder --mac

view raw JSON →