electron 5.0.0 “Uncaught ReferenceError: require is not defined”

前端 未结 6 886
难免孤独
难免孤独 2020-12-24 06:06

I had initially been using electron stable (4.x.x), and was able to use require in both my browser and renderer processes. I upgraded to electron beta (5.0.0) b

相关标签:
6条回答
  • 2020-12-24 06:29

    junvar is right, nodeIntegration is false by default in v5.0.0.

    It's the last statement in the Other Changes section of Release Notes for v5.0.0 and was also mentioned in this PR

    0 讨论(0)
  • 2020-12-24 06:29

    Add nodeIntegration: true and remove sandbox: true:

    mainWindow = new BrowserWindow({
      webPreferences: {
        nodeIntegration: true, // <---------- add this
        // sandbox: true <------------ remove this
      }
    });
    
    0 讨论(0)
  • 2020-12-24 06:37

    Readers of this post should read the Do not enable Node.js Integration for Remote Content section from the Security, Native Capabilities, and Your Responsibility Guide before making a decision.

    // Bad
    const mainWindow = new BrowserWindow({
      webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: true
      }
    })
    mainWindow.loadURL('https://example.com')
    
    // Good
    const mainWindow = new BrowserWindow({
      webPreferences: {
        preload: path.join(app.getAppPath(), 'preload.js')
      }
    })
    mainWindow.loadURL('https://example.com')
    
    0 讨论(0)
  • 2020-12-24 06:48

    It turns out, nodeIntegration was true by default in previous electron versions, but false by default in 5.0.0. Consequently, setting it to true resolved my issue. Not finding this change documented online in comments or on electrons page, I thought I'd make this self-answered SO post to make it easier to find for future people who encounter this issue.

    0 讨论(0)
  • 2020-12-24 06:52

    Like junvar said, nodeIntegration is now false by default in 5.0.0.

    The electronjs FAQ has some sample code on how to set this value.

    let win = new BrowserWindow({
      webPreferences: {
        nodeIntegration: true
      }
    })
    win.show()
    
    0 讨论(0)
  • 2020-12-24 06:53

    set nodeIntegration to true when creating new browser window.

    app.on('ready', () => {
        mainWindow = new BrowserWindow({
            webPreferences: {
                nodeIntegration: true
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题