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

Electron+TypeScript项目中window.require导入serialport的类型支持问题

解决Electron渲染进程中SerialPort的TypeScript类型配置问题

核心问题分析

Electron渲染进程在禁用nodeIntegration或开启contextIsolation时,无法直接通过import引入Node.js模块(如serialport),只能通过window.require或预加载脚本暴露的全局对象访问,但TypeScript类型校验会出现不匹配问题。

正确配置方案

1. 安装必要类型依赖

确保已安装相关类型包:

npm install -D @types/serialport @types/electron @types/node

2. 配置全局Window类型声明

在项目的类型目录(如src/types)下创建window.d.ts,正确扩展全局Window接口:

import type { SerialPort, SerialPortOpenOptions } from 'serialport';

declare global {
  // 声明window.require的类型,指定加载serialport时的返回值类型
  interface NodeRequire {
    (module: 'serialport'): typeof import('serialport');
  }

  interface Window {
    require: NodeRequire;
  }
}

// 确保文件被当作模块处理
export {};

3. 调整tsconfig.json配置

确保TypeScript能识别自定义类型文件和Node.js/Electron类型:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "esModuleInterop": true,
    "typeRoots": ["./node_modules/@types", "./src/types"],
    "types": ["node", "electron"],
    "include": ["src/**/*"]
  }
}

4. 渲染进程中正确使用SerialPort

现在可以直接通过window.require获取类型正确的SerialPort:

// 渲染进程代码
const { SerialPort } = window.require('serialport');

// 实例化时类型校验正常
const port = new SerialPort({
  path: '/dev/ttyUSB0',
  baudRate: 9600
});

// 事件监听和方法调用都能获得类型提示
port.on('open', () => {
  console.log('串口已打开');
});

port.write('hello', (err) => {
  if (err) console.error('写入失败:', err);
});

进阶:开启contextIsolation时的配置

如果你的Electron开启了contextIsolation: true,window.require会被禁用,需要通过预加载脚本暴露SerialPort:

预加载脚本(preload.ts)

import { contextBridge } from 'electron';
import * as Serialport from 'serialport';

contextBridge.exposeInMainWorld('electronAPI', {
  SerialPort: Serialport.SerialPort
});

更新window.d.ts声明

import type { SerialPort } from 'serialport';

declare global {
  interface Window {
    electronAPI: {
      SerialPort: typeof SerialPort;
    };
  }
}

export {};

渲染进程使用

const { SerialPort } = window.electronAPI;
const port = new SerialPort({ path: '/dev/ttyUSB0', baudRate: 9600 });

为什么之前的方案会出错

  • 未正确声明window.require('serialport')的返回类型,导致TypeScript无法推断出SerialPort的正确类类型,出现typeof SerialPort的类型混淆。
  • 自定义类型文件未被TypeScript识别,或未引入serialport的官方类型定义,导致方法类型无法被识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:30:49