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

使用electron-builder构建时遇@serialport非Win32应用错误

Electron串口应用构建问题

问题1:Linux交叉编译Windows版本无法启动

Linux环境下用electron-builder构建Windows版本成功,但生成的应用启动时报错:@serialport ... is not Win32 application

问题2:Windows本地构建失败

Windows环境执行构建时,重建@serialport/bindings-cpp@12.0.1出现spawn EINVAL错误,导致构建终止。


Windows构建错误日志

C:\Users\Win\Desktop\1.2.5>npm run build
> market-app@1.2.5 build
> electron-builder --win
• electron-builder  version=24.13.3 os=10.0.19045
• loaded configuration  file=package.json ("build" field)
• @electron/rebuild not required if you use electron-builder, please consider to remove excess dependency from devDependencies
To ensure your native dependencies are always matched electron version, simply add script `"postinstall": "electron-builder install-app-deps" to your `package.json`
• writing effective config  file=dist\builder-effective-config.yaml
• rebuilding native dependencies  dependencies=@serialport/bindings-cpp@12.0.1 platform=win32 arch=x64
⨯ cannot execute  cause=exit status 1
errorOut=npm error code 1
npm error path C:\Users\Win\Desktop\1.2.5\node_modules\@serialport\bindings-cpp
npm error command failed
npm error command C:\Windows\system32\cmd.exe /d /s /c node-gyp-build
npm error node:internal/child_process:421
npm error     throw new ErrnoException(err, 'spawn');
npm error     ^
npm error
npm error Error: spawn EINVAL
npm error     at ChildProcess.spawn (node:internal/child_process:421:11)
npm error     at Object.spawn (node:child_process:761:9)
npm error     at build (C:\Users\Win\Desktop\1.2.5\node_modules\@serialport\bindings-cpp\node_modules\node-gyp-build\bin.js:29:8)
npm error     at preinstall (C:\Users\Win\Desktop\1.2.5\node_modules\@serialport\bindings-cpp\node_modules\node-gyp-build\bin.js:38:32)
npm error     at Object.<anonymous> (C:\Users\Win\Desktop\1.2.5\node_modules\@serialport\bindings-cpp\node_modules\node-gyp-build\bin.js:15:3)
npm error     at Module._compile (node:internal/modules/cjs/loader:1546:14)
npm error     at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
npm error     at Module.load (node:internal/modules/cjs/loader:1317:32)
npm error     at Module._load (node:internal/modules/cjs/loader:1127:12)
npm error     at TracingChannel.traceSync (node:diagnostics_channel:315:14) {
npm error   errno: -4071,
npm error   code: 'EINVAL',
npm error   syscall: 'spawn'
npm error }
npm error
npm error Node.js v22.6.0
npm error A complete log of this run can be found in: C:\Users\Win\AppData\Local\npm-cache\_logs\2024-08-19T20_47_08_788Z-debug-0.log

                command='C:\Program Files\nodejs\node.exe' 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js' rebuild @serialport/bindings-cpp@12.0.1
                workingDir=
C:\Users\Win\Desktop\1.2.5>

Linux构建日志

linux-mysistem:~/Desktop/Market App$ npm run build
> market-app@1.2.5 build
> electron-builder --win
• electron-builder  version=24.13.3 os=6.8.0-40-generic
• loaded configuration  file=package.json ("build" field)
• @electron/rebuild not required if you use electron-builder, please consider to remove excess dependency from devDependencies
To ensure your native dependencies are always matched electron version, simply add script `"postinstall": "electron-builder install-app-deps" to your `package.json`
• writing effective config  file=dist/builder-effective-config.yaml
• skipped dependencies rebuild  reason=platform is different and buildDependenciesFromSource is set to true
• packaging       platform=win32 arch=x64 electron=31.4.0 appOutDir=dist/win-unpacked
• building        target=nsis file=dist/Market App Setup 1.2.5.exe archs=x64 oneClick=false perMachine=false
• building block map  blockMapFile=dist/Market App Setup 1.2.5.exe.blockmap

package.json配置

{
"name": "my-app",
"version": "1.2.5",
"description": "My app description",
"main": "main.js",
"scripts": {
  "start": "electron main.js",
  "dist": "electron-builder",
  "build": "electron-builder --win",
  "pack": "electron-builder --win --dir",
  "postinstall": "electron-builder install-app-deps",
  "rebuild": "electron-rebuild -f -w serialport"
},
"build": {
  "appId": "com.name.app",
  "productName": "My App",
  "buildDependenciesFromSource": true,
  "win": {
    "icon": "assets/icon.png"
  },
  "nsis": {
    "oneClick": false,
    "allowToChangeInstallationDirectory": false,
    "license": "assets/LICENSE.txt",
    "installerIcon": "assets/icon-installer.ico",
    "installerHeaderIcon": "assets/icon-installer.ico",
    "uninstallerIcon": "assets/icon-uninstaller.ico",
    "installerSidebar": "assets/sidebar.png",
    "uninstallerSidebar": "assets/sidebar.png"
  },
  "files": [
    "main.js",
    "package.json",
    "node_modules/**",
    "scripts/**",
    "pages/**",
    "assets/**"
  ]
},
"devDependencies": {
  "@types/electron-prompt": "^1.6.5",
  "@types/fs-extra": "^11.0.4",
  "@types/nedb": "^1.8.16",
  "@types/node-schedule": "^2.1.7",
  "electron": "^31.2.1",
  "electron-builder": "^24.13.3",
  "electron-rebuild": "^3.2.9"
},
"dependencies": {
  "electron-prompt": "^1.7.0",
  "fs-extra": "^11.1.1",
  "nedb": "^1.8.0",
  "node-schedule": "^2.1.1",
  "serialport": "^12.0.0"
}
}

串口操作核心代码

const { SerialPort } = require('serialport');
const { ReadlineParser } = require('@serialport/parser-readline');

// 扫描可用串口
async function listPorts() {
  try {
    const ports = await SerialPort.list();
    return ports.map(port => ({
      path: port.path,
      manufacturer: port.manufacturer || '未知厂商'
    }));
  } catch (err) {
    console.error('扫描串口失败:', err);
    return [];
  }
}

// 打开串口并监听数据
function openPort(portPath, baudRate = 9600) {
  const port = new SerialPort({
    path: portPath,
    baudRate: baudRate,
    autoOpen: false
  });

  const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }));

  port.open(err => {
    if (err) {
      console.error('打开串口失败:', err);
      return;
    }
    console.log('串口已打开:', portPath);
  });

  parser.on('data', data => {
    console.log('收到数据:', data.trim());
    // 此处处理秤的输入数据
  });

  port.on('error', err => {
    console.error('串口错误:', err);
  });

  port.on('close', () => {
    console.log('串口已关闭');
  });

  return port;
}

module.exports = { listPorts, openPort };

解决方案

针对问题1:Linux交叉编译Windows版本无法启动

原因:buildDependenciesFromSource: true 配置下,Linux环境默认缺少Windows交叉编译工具链,electron-builder跳过了serialport原生绑定的重建,导致打包了Linux版本的二进制文件,Windows无法识别运行。

解决步骤:

  1. 安装Windows交叉编译依赖(Debian/Ubuntu环境):
sudo apt-get install gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64
  1. 修改package.json的build配置,添加远程构建支持:
"build": {
  // 保留原有配置
  "remoteBuild": true,
  "buildDependenciesFromSource": true
}
  1. 清理依赖后重新构建:
rm -rf node_modules package-lock.json
npm install
npm run build

针对问题2:Windows本地构建出现spawn EINVAL错误

原因:Node.js v22为最新版本,与node-gyp-build存在兼容性问题;或Windows环境缺少C++编译工具链。

解决步骤:

  1. 降级Node.js到LTS版本(推荐v20.x),避免新版本API兼容问题。
  2. 安装Windows编译工具链:
    • 以管理员权限打开PowerShell,执行:
    npm install --global windows-build-tools
    
    或通过Visual Studio Installer安装「Desktop development with C++」工作负载,确保包含MSVC工具链、Windows SDK。
  3. 清理缓存并重新安装依赖:
Remove-Item -Recurse node_modules, package-lock.json
npm cache clean --force
npm install
npm run build
  1. 若仍报错,修改postinstall脚本指定electron-rebuild处理serialport:
"scripts": {
  // 保留原有脚本
  "postinstall": "electron-rebuild -f -w serialport"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:29:55