All posts

Fix Missing Import in Electron

Resolve module import errors in Electron apps caused by main/renderer process confusion, Node.js integration, and preload script issues.

Missing Import Errors in Electron

Electron has two process types — main and renderer — each with different module access. Importing a main-process module in the renderer (or vice versa) causes confusing errors.

Main Process vs Renderer Process

// WRONG — 'app' only works in main process
// renderer.ts
import { app } from 'electron'; // Error: Cannot find module

// RIGHT — use ipcRenderer in renderer
import { ipcRenderer } from 'electron';
// But only if nodeIntegration is enabled (not recommended)

With Context Isolation (Recommended)

// preload.ts — bridge between main and renderer
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electronAPI', {
  getAppVersion: () => ipcRenderer.invoke('get-app-version'),
  openFile: () => ipcRenderer.invoke('dialog:openFile'),
});
// main.ts — handle the IPC
ipcMain.handle('get-app-version', () => {
  return app.getVersion();
});
// renderer.ts — use the exposed API
const version = await window.electronAPI.getAppVersion();

Node.js Modules in Renderer

// Can't use 'fs' directly in renderer with contextIsolation
// Instead, expose specific functions via preload:
contextBridge.exposeInMainWorld('fs', {
  readFile: (path: string) => ipcRenderer.invoke('read-file', path),
});

TypeScript Declarations

// src/types/electron.d.ts
declare global {
  interface Window {
    electronAPI: {
      getAppVersion: () => Promise<string>;
      openFile: () => Promise<string | undefined>;
    };
  }
}

Bugsly captures import errors in both Electron processes, correlating main process crashes with renderer-side error reports.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free