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

Electron打包后onnxruntime-node无法调用InferenceSession.create求助

解决Electron打包后onnxruntime-node无法加载的问题

问题根源

Electron打包工具默认不会自动处理onnxruntime-node这类包含平台特定二进制文件和依赖库(.dll)的包,导致打包后Node无法找到对应的模块和依赖;直接引用底层的onnxruntime_binding.node会丢失上层JS封装的API(比如InferenceSession),因此出现TypeError: ort.InferenceSession.create is not a function。

解决步骤

1. 配置打包工具,包含onnxruntime-node的二进制文件和依赖dll

以electron-builder为例,在项目的package.json中添加build配置,将对应平台的onnxruntime资源复制到打包后的资源目录:

"build": {
  "extraResources": [
    {
      "from": "node_modules/onnxruntime-node/bin/napi-v3/win32/x64/",
      "to": "resources/onnxruntime/",
      "filter": ["*.node", "*.dll"]
    }
  ]
}
  • from:根据你的Node API版本(可通过process.versions.napi查看)、系统平台调整路径,示例为Windows x64环境。
  • filter:确保包含.node二进制文件和所有依赖的.dll。

2. 调整代码中的导入逻辑,正确加载onnxruntime-node

不要直接引用onnxruntime_binding.node,而是通过Electron的资源路径加载完整的onnxruntime模块,同时确保依赖的dll能被找到:

const { app } = require('electron');
const path = require('path');

// 获取打包后的onnxruntime资源目录
const onnxRuntimeDir = path.join(app.getAppPath(), 'resources', 'onnxruntime');
// 将dll所在目录加入PATH,确保Node能加载依赖库
process.env.PATH = `${onnxRuntimeDir}${path.delimiter}${process.env.PATH}`;

// 正确导入onnxruntime-node的封装模块
const ort = require('onnxruntime-node');

// 后续推理逻辑保持不变
const modelPath = path.join(__dirname, 'model.onnx');
const session = await ort.InferenceSession.create(modelPath);

3. 验证打包配置

  • 打包后检查resources/onnxruntime目录下是否包含onnxruntime_binding.node和所有对应的.dll文件。
  • 确保开发环境和打包环境的Node版本、NAPI版本一致,避免二进制文件不兼容。

关键说明

  • 直接引用onnxruntime_binding.node只会得到底层的C++绑定,没有JS层封装的InferenceSession等API,必须通过onnxruntime-node的主模块导入。
  • .dll文件是onnxruntime运行时的依赖,必须和.node文件一起打包并让系统能找到(通过设置PATH)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:22:08