Electron启动报错:TypeError: Cannot read properties of undefined (reading 'whenReady')
问题分析与修复方案
报错TypeError: Cannot read properties of undefined (reading 'whenReady')的核心原因是错误使用异步import()语法,而非chapter3.mjs的导入问题。你直接对import('electron')的返回值(Promise对象)进行解构,导致app变量为undefined,调用app.whenReady()自然触发报错。path的导入也存在同样问题。
具体修复步骤:
- 将
electron和node:path的异步导入改为静态ES模块导入,因为这两个模块需要同步加载并立即使用。 - 确保
chapter3.mjs中正确导出magicEightBall函数(比如使用export function magicEightBall() {...})。
修正后的main.mjs代码:
// Modules to control application life and create native browser window import { magicEightBall } from './chapter3.mjs'; import { app, BrowserWindow } from 'electron'; import path from 'node:path'; function createWindow () { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html'); // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow(); magicEightBall(); app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.
额外检查:
确认chapter3.mjs的导出格式正确,示例如下:
export function magicEightBall() { // 你的函数逻辑 console.log('magicEightBall 执行'); }
执行npm start后,Electron应用将正常启动,同时magicEightBall函数也会被执行。
内容的提问来源于stack exchange,提问作者j_falcon
相关产品推荐
相关产品推荐

