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:
- 修改main.js的webPreferences配置:
const win = new BrowserWindow({ webPreferences: { nodeIntegration: false, contextIsolation: true, // 为默认值可省略 preload: path.join(__dirname, "preload.js") }, });
- 编辑preload.js文件,通过
contextBridge暴露需要的IPC能力:
const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('electronAPI', { submitValidation: (data) => ipcRenderer.send('validation', data) // 其余需要调用的能力可在此处统一暴露 });
- 修改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
相关产品推荐
相关产品推荐

