You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron Forge问题:TypeScript-Webpack模板下渲染器用ipcRenderer报错

Fixing "Uncaught ReferenceError: require is not defined" in Electron TypeScript-Webpack App

Hey there, let's work through this issue together. That error pops up because modern Electron disables Node.js integration in the renderer process by default (for security reasons)—so require() simply doesn't exist in that environment. Your attempt with webpack.ExternalsPlugin won't fix it here because the renderer doesn't have access to Node.js APIs at all in this default setup.

Here's the secure, recommended way to resolve this:

1. Update Main Process Configuration

First, tweak your main process (main.ts) to use a preload script while keeping context isolation enabled (this is the safest approach per Electron's guidelines):

// src/main.ts
import { app, BrowserWindow } from 'electron';
import path from 'path';

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // Path to your preload script (adjust if your project structure differs)
      preload: path.join(__dirname, 'preload.js'),
      // Keep these enabled for security
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.loadFile('index.html');
}

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

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

2. Create a Preload Script

The preload script runs in a special context that has access to both Electron/Node.js APIs and the renderer's window. We'll use contextBridge to safely expose only the specific APIs our renderer needs:

Create src/preload.ts with this code:

import { contextBridge, ipcRenderer } from 'electron';

// Expose a limited, safe set of IPC methods to the renderer
contextBridge.exposeInMainWorld('electronAPI', {
  // Example method to send messages to the main process
  send: (channel: string, data: unknown) => {
    ipcRenderer.send(channel, data);
  },
  // Example method to listen for messages from the main process
  receive: (channel: string, callback: (...args: unknown[]) => void) => {
    const subscription = (_event: Electron.IpcRendererEvent, ...args: unknown[]) => callback(...args);
    ipcRenderer.on(channel, subscription);

    // Return a cleanup function to remove the listener later
    return () => ipcRenderer.removeListener(channel, subscription);
  }
});

3. Add Type Definitions for the Exposed API

To get proper TypeScript support in the renderer, create a type definition file (e.g., src/types/global.d.ts):

export interface ElectronAPI {
  send: (channel: string, data: unknown) => void;
  receive: (channel: string, callback: (...args: unknown[]) => void) => () => void;
}

declare global {
  interface Window {
    electronAPI: ElectronAPI;
  }
}

4. Update Renderer Code to Use the Exposed API

Instead of importing ipcRenderer directly in renderer.ts, use the safely exposed electronAPI from the window object:

// src/renderer.ts
import "./index.css";

// Send a message to the main process
window.electronAPI.send('test-channel', 'Hello from the renderer!');

// Listen for responses from the main process
const cleanupListener = window.electronAPI.receive('reply-channel', (data) => {
  console.log('Received from main process:', data);
});

// Clean up the listener when it's no longer needed
// cleanupListener();

5. Verify Webpack Configuration

The create-electron-app TypeScript-Webpack template should automatically handle bundling the preload script, but double-check that your preload file is included in the build process. If you need to adjust manually, ensure the webpack config treats the preload as a separate entry (the template usually does this by default).

Once you make these changes, run npm run start again—the require is not defined error should be gone. This approach follows Electron's security best practices by keeping context isolation enabled and only exposing the exact APIs your renderer needs.

内容的提问来源于stack exchange,提问作者undefined

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:27:47