简体   繁体   中英

Electron require is not defined in renderer process

I'm starting with electron and for some unknown reason I can't use require() function in renderer process.

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

I am doing everything like in the tutorial, I have searched for solution for two days and tried everything, nothing works. I am worried that only I have that problem:v

There's a typo in nodeIntegration (you spelled it nodeIntergration ). That's probably the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM