如何在Electron应用中加载.node原生扩展?

前端开发 2026-07-10

在Vite 7下,我用下列方式加载一个.node原生模块:

import {createRequire} from "node:module";
const rq = createRequire(import.meta.url);
const addon = rq("../build/Release/native") as NativeModule;

现在在Vite 8下,即使是在Electron主进程的普通TS模块中,inport.meta.url 也未定义,且它不是一个UMD/IIFE模块。

官方给出的变通方法是在 vite.config.ts 上添加如下:

        rolldownOptions: {
            output: {
                intro: `
          if (typeof import.meta === 'undefined' || import.meta.url === undefined) {
            // @ts-ignore
            import.meta.url = new URL('file:' + __filename).href;
          }
        `,

但不起作用。另外,定义一个自定义Vite插件来转换对.node文件的普通导入的建议也无效,并且会报错说 import addon from '../build/Release/native.node' 无法解析native.node
是否存在官方的方式来加载Node原生模块?

解决方案

Solved! Here are the steps if they could be helpful to someone:

  1. 在vite.config.ts中,在 rolldownOptions.output 处添加以下行:intro: `globalThis.modulePath = new URL('file:' + __filename).href`
  2. 在代码中将每个 import.meta.url 替换为 (globalThis as unknownas {modulePath: string}).modulePath;

这样就能正确加载插件。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章