Electron应用引入JS脚本出现ReferenceError: require is not defined错误求助
解决Electron渲染进程中
ReferenceError: require is not defined的问题 出现这个错误的核心原因是:Electron 12及以后版本默认在渲染进程中禁用了Node.js集成(nodeIntegration: false),同时启用了上下文隔离(contextIsolation: true),导致渲染进程无法直接调用require加载Node.js模块。
下面提供两种解决方案,优先推荐安全的预加载脚本方案:
方案一:临时开启Node.js集成(不推荐,存在安全风险)
如果只是开发测试场景,可以修改主进程中BrowserWindow的配置,强制开启Node.js集成并关闭上下文隔离:
const { app, BrowserWindow } = require('electron') function createWindow() { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: 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() })
修改后,你的computer.js里的const os = require("os")就能正常运行,但这种方式会让渲染进程获得完整的Node.js权限,若页面加载不可信内容,会引发安全问题,正式环境禁止使用。
方案二:使用预加载脚本(推荐,安全合规)
通过Electron的预加载(preload)脚本,在上下文隔离开启的前提下,安全地将Node.js模块的API暴露给渲染进程:
步骤1:创建预加载脚本preload.js
const { contextBridge } = require('electron') const os = require('os') // 向渲染进程暴露指定的API,避免直接暴露完整Node.js权限 contextBridge.exposeInMainWorld('electronAPI', { getComputerInfo: () => ({ platform: os.platform(), arch: os.arch(), totalMemory: os.totalmem(), freeMemory: os.freemem() // 可根据需求添加更多os模块的方法 }) })
步骤2:修改主进程配置,指定预加载脚本
const { app, BrowserWindow } = require('electron') const path = require('path') function createWindow() { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 配置预加载脚本路径,__dirname指向主进程文件所在目录 preload: path.join(__dirname, 'preload.js') // 默认保持contextIsolation: true,无需额外修改 } }) 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() })
步骤3:在渲染进程中调用暴露的API
修改你的computer.js,不再使用require,直接调用预加载脚本暴露的全局API:
// 获取电脑信息 const computerInfo = window.electronAPI.getComputerInfo() // 将信息展示到页面示例 document.getElementById('platform').textContent = `系统平台:${computerInfo.platform}` document.getElementById('arch').textContent = `CPU架构:${computerInfo.arch}` document.getElementById('total-mem').textContent = `总内存:${(computerInfo.totalMemory / 1024 / 1024 / 1024).toFixed(2)} GB` document.getElementById('free-mem').textContent = `空闲内存:${(computerInfo.freeMemory / 1024 / 1024 / 1024).toFixed(2)} GB`
对应的HTML可添加展示元素:
<div class="computer-info"> <p id="platform"></p> <p id="arch"></p> <p id="total-mem"></p> <p id="free-mem"></p> </div> <script src="../scripts/computer.js"></script>
这种方式既满足了获取Node.js模块数据的需求,又通过上下文隔离限制了权限范围,符合Electron的安全规范。
内容的提问来源于stack exchange,提问作者Maciex
相关产品推荐
相关产品推荐

