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

Electron 19.0.6遇require is not defined报错排查求助

问题现象

开发Electron应用时点击按钮触发页面加载,出现文件找不到的错误:
遇到的错误提示

触发错误的代码如下:

document.getElementById('settings').addEventListener('click', () => {
  remote.getFocusedWindow().loadFile('/settings/settings.html')
});

已在main.js中开启nodeIntegration配置。

问题成因

核心原因是loadFile的路径解析规则和常规前端静态路径规则不一致:

  • 传入以/开头的路径时,Electron会将其识别为操作系统的根目录绝对路径,而非项目根目录路径。比如Windows下会去找C:\settings\settings.html,macOS/Linux下会去找/settings/settings.html,这个路径下不存在对应文件,就会抛出ERR_FILE_NOT_FOUND错误。
  • 额外注意:Electron 14及以上版本默认禁用remote模块,仅开启nodeIntegration不足以让remote模块正常工作,后续还可能触发remote未定义的报错。
修复方案
  • 修正文件路径,不要使用以/开头的系统根路径,推荐两种稳妥写法:
    1. 相对路径写法:根据当前执行脚本的目录层级调整,若当前加载的页面位于项目根目录,直接去掉路径开头的/即可
    document.getElementById('settings').addEventListener('click', () => {
      remote.getFocusedWindow().loadFile('settings/settings.html')
    });
    
    1. 绝对路径拼接写法:通过node自带的path模块拼接项目的真实绝对路径,完全不受文件层级影响,稳定性最高
    const path = remote.require('path');
    const appRootPath = remote.app.getAppPath();
    document.getElementById('settings').addEventListener('click', () => {
      remote.getFocusedWindow().loadFile(path.join(appRootPath, 'settings', 'settings.html'))
    });
    
  • 高版本Electron补全必要配置,在main.js的BrowserWindow配置项中添加缺失的配置项:
    const mainWindow = new BrowserWindow({
      // 其他窗口尺寸、标题等配置...
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false, // 开启nodeIntegration时必须关闭上下文隔离,否则node API无法在渲染进程访问
        enableRemoteModule: true // Electron14+必须显式开启才能使用remote模块
      }
    })
    

最佳实践提示:生产环境不推荐在渲染进程直接通过remote操作主进程窗口对象,建议通过IPC通信的方式,由主进程接收渲染进程的跳转事件后自行调用窗口的loadFile方法,安全性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:12:18