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

electron-react-boilerplate v4.0.0 调用window.electron提示不存在报错如何解决

错误原因

该报错属于TypeScript类型定义缺失问题,并不代表运行时无法调用对应API:你在preload脚本中通过contextBridge挂载到window对象的electron属性,没有被TypeScript默认的Window类型收录,因此IDE/编译阶段会抛出类型错误。

解决方案

步骤1:新增全局类型声明文件

在项目src目录下新建名为global.d.ts的类型声明文件,写入以下内容:

export {}

declare global {
  interface Window {
    electron: {
      ipcRenderer: {
        // 对应你暴露的printTicket方法,可根据实际返回值调整类型
        printTicket: () => void
        // 其他你在preload中暴露的ipcRenderer方法也可以在此补充类型
        send: (channel: string, ...args: any[]) => void
        on: (channel: string, listener: (...args: any[]) => void) => void
        removeListener: (channel: string, listener: (...args: any[]) => void) => void
      }
    }
  }
}

步骤2:确认声明文件被TS识别

打开项目根目录的tsconfig.json,检查include配置项,确保包含了src目录下的所有类型声明文件,示例配置如下:

{
  "compilerOptions": {
    // 原有配置保持不变
  },
  "include": [
    "src/**/*",
    "src/**/*.d.ts"
  ]
}

步骤3:重启TypeScript服务

如果修改后IDE依然提示报错,重启TypeScript语言服务即可:以VSCode为例,按快捷键Ctrl+Shift+P(Mac为Command+Shift+P),输入TypeScript: Restart TS Server执行即可。

运行时异常排查补充

如果按照以上步骤处理后,实际运行时依然提示window.electron不存在,请检查两项配置:

  • 主进程创建BrowserWindow时,webPreferences配置项的contextIsolation为true、nodeIntegration为false,且preload字段的文件路径配置正确
  • preload脚本中contextBridge.exposeInMainWorld的第一个参数确实为electron,和你调用的属性名完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:36:00