环境:Electron 7

使用 Create-React-App 模板

运行时发生的错误:

TypeError: fs.existsSync is not a function

Electron中require报错的解决与分析

  • 发生错误的代码(在 render 进程中):
const {desktopCapturer} = require('electron')
  • 处理方法:
const {desktopCapturer} = window.require('electron')

 


 

在 Electron 的 Issue #7300 中找到了解决方案,作为一名 Electron 以及 Web 前端的初学者,自然要在此问题上稍加分析,争取多了解一些背景知识,提高学习质量。

  • 此问题出现的原因为:nodejs 运行时的 require 与编译时 webpack 的 require 是不同的。默认情况下,window 是全局的,然而在 webpack 编译时会忽略 window 
  • 其他的解决方案:使用 preload 方法
  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });

在 preload.js 文件中将要使用的模块引入即可

window.ipcRenderer = require('electron').ipcRenderer;

 

相关文章:

  • 2022-12-23
  • 2021-04-14
  • 2022-12-23
  • 2021-10-17
  • 2021-06-23
  • 2022-12-23
  • 2021-12-27
  • 2021-05-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-04
  • 2022-01-10
  • 2021-09-29
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案