gpt4 book ai didi

javascript - 不能在 Electron.js 中使用导出和导入

转载 作者:行者123 更新时间:2023-12-04 17:12:12 28 4
gpt4 key购买 nike

这是我的主要(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")
})

现在,我无法使用导入/导出。

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

如果我删除导出/导入行,它会正常工作,正如预期的那样

(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)
}

另一个.js

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

updateFunction("Hellow")

My File Structure

最佳答案

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

  • 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 imports 和 exports 因为它们更容易理解,但那是另一回事。

关于javascript - 不能在 Electron.js 中使用导出和导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69224302/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com