渲染器进程中未定义Electron require

lf5gs5x2  于 12个月前  发布在  Electron
关注(0)|答案(2)|浏览(152)

我从电子开始,由于一些未知的原因,我不能在渲染过程中使用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"
  }
}

main.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

icnyk63a

icnyk63a1#

nodeIntegration中有一个错别字(您将其拼写为nodeIntergration)。这可能是问题所在

xriantvc

xriantvc2#

也许可以尝试从preload.js脚本中获取ipcRenderer,然后使用contextBridge将其暴露给环境。

//preload.js
const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("myappvar",{
  close:()=>ipcRenderer.invoke("closeApp"),
});

字符串
然后,在main中,您可以创建一个ipcMain来处理closeApp调用,并且在应用程序中的任何其他地方,您都可以使用myappvar.close()window.myappvar.close()引用该函数
main的例子:

// main.js
const { app, ipcMain } = require('electron')

/* omitted some code stuff before */

ipcMain.handle('closeApp',()=>{
    if (process.platform !== 'darwin') app.quit();
})

/* More stuff after */


最后,正如另一位用户@bubs16458指出的in this comment,尝试将您的错字从 * nodeIntergration * 修复为**nodeIntegration**
试试这些,看看是否都适合你!美好的一天!

相关问题