mac环境下electron报错Uncaught ReferenceError: require is not defined

Augular搭建的项目,通过 ng serve -o 启动项目,提示Compiled successfully,但首页就loading不进去,查看了一下console,提示Uncaught ReferenceError: require is not defined,如下图

image.png

google、度娘了一下,基本千遍一律找到都是说把 nodeIntegration 改为true,

看别人说原因是

因为渲染进程使用require引入node的模块,这时会报错Uncaught ReferenceError: require is not defined。原因应该是加载渲染进程的窗口没有集成node环境。

但问题是我本来设置就是true,这个选项没有任何效果

附上部分相关代码

// main.js 部分代码

mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  })
  
//下面是preload.js的代码

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  } 
  
  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

系统:
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G87

工具版本
Angular CLI: 8.3.20
Node: 10.16.3
OS: darwin x64
Angular: 8.2.14
electron: 6.1.5

阅读 7.3k
1 个回答

试试 window.require

注意:window小写
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题