【问题标题】:Electron require is not defined in renderer process渲染器进程中未定义电子需求
【发布时间】:2021-07-06 10:24:32
【问题描述】:

我从 electron 开始,由于某些未知原因,我不能在渲染器进程中使用 require() 函数。

Uncaught ReferenceError: require is not defined at index.js:1

package.json

{
  "name": "my-electron-app",
  "version": "0.1.0",
  "author": "your name",
  "description": "My Electron app",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [],
  "license": "ISC",
  "devDependencies": {
    "electron": "^12.0.2"
  }
}

ma​​in.js

const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntergration: true, 
      contextIsolation: false,
      devTools: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('index.html')
  
    win.webContents.openDevTools()

  ipc.on("closeApp", ()=>{
    console.log("clicked on Close btn")
    win.close();
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
</head>
<body style="background: white;">
    <h1>Hello World!</h1>
    <p>
        We are using Node.js <span id="node-version"></span>,
        Chromium <span id="chrome-version"></span>,
        and Electron <span id="electron-version"></span>.
    </p>
    <button id="closeBtn">close</button>
    
    <script defer src="index.js"></script>
</body>
</html>

index.js

const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;

var closeBtn = document.getElementById('closeBtn');

closeBtn.addEventListener("click", ()=>{
    ipc.send("closeApp");
});

Screenshot of my program

我正在按照教程中的方式进行操作,我已经搜索了两天的解决方案并尝试了所有方法,但没有任何效果。我担心只有我有这个问题:v

【问题讨论】:

  • 我认为这是因为 nodeIntegration 已禁用。也许教程很旧。
  • 很奇怪。如果禁用任何一个节点或启用上下文隔离,通常会发生这种情况,但看起来您正在正确启用/禁用它们。您确定您发布的代码与您所拥有的完全一致吗?
  • 是的,我检查了 3 次。我应该重新安装 node.js 吗?

标签: javascript electron


【解决方案1】:

nodeIntegration 中有错字(你拼写为nodeIntergration)。应该是这个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2016-08-06
    • 1970-01-01
    • 2020-04-26
    • 2021-07-22
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多