You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次开发Electron应用运行报错:TypeError [ERR_INVALID_ARG_TYPE]求排查

问题分析与解决方案

这个报错的根源其实是个很容易忽略的小细节——你在导入Electron核心模块时犯了参数类型错误:

看你代码里的这两行:

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

第二行的require(electron)是问题核心:require()方法要求传入的必须是字符串类型的模块名称,但你这里传的是已经被导入的electron对象,这就直接触发了ERR_INVALID_ARG_TYPE类型错误。

两种简单修正方案:

  • 方案一:直接从已导入的electron对象中解构,无需重复调用require
    const electron = require("electron");
    const { app, BrowserWindow } = electron;
    
  • 方案二:更简洁的写法,直接在require时完成解构
    const { app, BrowserWindow } = require("electron");
    
    这种写法可以删掉第一行多余的const electron = require("electron");,让代码更精简。

修正后的完整可运行代码:

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

let createWindow = () => {
  let window = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });
  // 加载本地index.html文件
  window.loadFile("index.html");
  // 打开开发者工具
  window.webContents.openDevTools();
};

app.whenReady().then(createWindow);

// 所有窗口关闭时退出应用(macOS除外)
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

// 注意:这里你原来的事件名写错了!正确事件名是"activate"而非"active"
app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

额外提醒一个小问题:你原来代码里最后一个事件监听写的是app.on("active", ...),这是错误的——Electron在macOS上触发的窗口激活事件名是activate,少一个字母会导致macOS上关闭窗口后点击Dock图标无法重新打开应用,我已经在上面的代码里同步修正了这个问题。

内容的提问来源于stack exchange,提问作者harsh_broh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:38:16