electron使用require报错undefined

我按照官网示例建了一个electron的hello world应用程序,但是在index.html里我在脚本中写入const fs=require('fs')却报错

Uncaught ReferenceError: require is not defined
这是为什么呢?文档中不是说可以用nodejs的吗?
贴上我的index.js代码

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

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: true
    }
  })

  win.loadFile('index.html')
}

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

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

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
阅读 4.5k
2 个回答

经过我半天的测试,我发现package.json里安装的@electron-forge/cli,怎么测都是统一的undefined。然后我重新安装了"electron-forge": "^5.2.4",其它代码都是一模一样的,就没报错了。难道是版本问题?现在贴下package.json的配置,供后来人参考:

{
  "name": "test_electron",
  "version": "1.0.0",
  "main": "index.js",
  "author": "zy",
  "license": "MIT",
  "dependencies": {
    "electron-forge": "^5.2.4"
  },
  "devDependencies": {
    "electron-prebuilt-compile": "8.2.0"
  },
  "scripts": {
    "start": "electron-forge start"
  },
  "config": {
    "forge": {
      "packagerConfig": {}
    }
  }
}
新手上路,请多包涵
推荐问题
宣传栏