You need to enable JavaScript to run this app. Electron开启nodeIntegration仍报require is not defined错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Electron开启nodeIntegration仍报require is not defined错误求助

问题原因

Electron 12及以上版本默认开启contextIsolation(上下文隔离),该配置优先级高于nodeIntegration,即便开启nodeIntegration,只要上下文隔离处于启用状态,渲染进程的JS上下文就无法直接访问Node.js API,所以会出现require is not defined报错。


解决方法

方案1:快速适配(存在安全风险,仅适合纯本地内容运行的场景)

修改main.js中BrowserWindow的webPreferences配置,新增contextIsolation: false:

const win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false, // 新增配置
    preload: path.join(__dirname, "preload.js")
  },
});

方案2:安全规范实现(推荐)

遵循Electron官方安全规范,不关闭上下文隔离、不启用nodeIntegration,通过preload脚本向渲染进程暴露所需的API:

  1. 修改main.js的webPreferences配置:
const win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: true, // 为默认值可省略
    preload: path.join(__dirname, "preload.js")
  },
});
  1. 编辑preload.js文件,通过contextBridge暴露需要的IPC能力:
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  submitValidation: (data) => ipcRenderer.send('validation', data)
  // 其余需要调用的能力可在此处统一暴露
});
  1. 修改main-login.js代码,移除require语句,直接调用暴露的全局API即可:
// 删除原有require语句,调用示例:window.electronAPI.submitValidation(登录参数)

(function ($) {
  "use strict";


  ...

  function hideValidate(input) {
    var thisAlert = $(input).parent();
    $(thisAlert).removeClass("alert-validate");
    $(thisAlert).find(".btn-hide-validate").remove();
  }
})(jQuery);

内容的提问来源于stack exchange,提问作者Hsu Chu Julio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 22:15:09