无法在 Electron.js 中使用导出和导入

Cannot use exports and imports in Electron.js

这是我的主要 (index.js) 文件:

const { app, BrowserWindow } = require("electron")

var mainWindow = null

app.on("ready", () => {
    mainWindow = new BrowserWindow({
        "width": 500,
        "height": 500,
        "webPreferences": {
            "nodeIntegration": true,
            "contextIsolation": false
        }
    })

    mainWindow.loadFile("src/html/welcome.html")
})

现在,我无法使用 import/exports。

每当我在上面的代码下面添加一个导出语句时,它会给出一个错误 Uncaught TypeError: Cannot read properties of undefined (reading 'on')

如果我删除 export/import 行,它会正常工作,正如预期的那样

(index.js)

const { app, BrowserWindow } = require("electron")

var mainWindow = null

app.on("ready", () => {
    mainWindow = new BrowserWindow({
        "width": 500,
        "height": 500,
        "webPreferences": {
            "nodeIntegration": true,
            "contextIsolation": false
        }
    })

    mainWindow.loadFile("src/html/welcome.html")
})

module.exports.updateFunction = (_name) => {
    console.log(_name)
}

another.js

const { updateFunction } = require("../../index");

updateFunction("Hellow")

我认为这里发生的是您正在为自己创建循环依赖。当您在加载模块时尝试遵循模块加载器正在采用(或试图采用)的路径时,这可能会有所帮助:

  • Electron 加载你的入口点index.js
    • 你的入口点加载了所有你使用过的子模块
      • 子模块 another.js 加载您的入口点模块 index.js

此时 index.js 尚未完全加载,因为必须首先加载其所有依赖项。循环依赖使模块加载器处于未定义状态,这取决于它的实现可能会导致各种错误。通常是

some.stuff is not a function
Cannot read property `XXX` of undefined
`XXX` does not exist
undefined index `#` of `XXX`

有多种方法可以解决这些错误,但最简单的方法是避免循环依赖。在你的情况下,创建一个你的 another.js 和你的 index.js 都可以导入的模块可能是最简单的:

// someModule.js
const { app, BrowserWindow } = require("electron")

let mainWindow = null

app.on("ready", () => {
    mainWindow = new BrowserWindow({
        "width": 500,
        "height": 500,
        "webPreferences": {
            "nodeIntegration": true,
            "contextIsolation": false
        }
    })

    mainWindow.loadFile("src/html/welcome.html")
})

// you can export mainWindow if you need it
module.exports.mainWindow = mainWindow;

module.exports.updateFunction = (_name) => {
    console.log(_name)
}
// index.js
const { mainWindow } = require('someModule');
// another.js
const { updateFunction } = require("../../someModule");

updateFunction("Hellow")

我还建议使用 Es6-style 导入和导出,因为它们更容易理解,但那是另一回事。