electron VIteJS导入本机编译节点模块失败“意外字符”

v09wglhw  于 9个月前  发布在  Electron
关注(0)|答案(1)|浏览(117)

我正在尝试将使用create-react-app构建的电子应用程序转换为ViteJS。到目前为止,我已经设法修复了很多东西,但我对我们的一个依赖关系有问题。
出于性能考虑,我的项目使用了一个内置在golang中的内部库,并且从电子应用程序的主进程调用该库。但是,当运行vite build时,我得到以下错误。

[commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript)

下面的代码行会发生这种情况

module.exports = require('./build/Release/goapi.node');

goapi.node是编译库。这个库是使用node-gyp编译的,我100%确定编译是正确的,因为它使用的是当前使用create-react-app的设置。
是否有插件添加到vite配置中以支持导入本机模块?如果没有,我如何解决这个问题?

a9wyjsp7

a9wyjsp71#

我在将node-pty添加到基于Electron Forge的Vite + TypeScript template的项目中时遇到了类似的问题。
我的解决方案是在Rollup配置中将node-pty标记为external,这会告诉Rollup将该模块保持在bundle的外部。
在我的“vite.main.config.ts”文件(专门用于编译Electron主进程)中,我在“defineConfig”中添加了一个“build”部分来定义这个Rollup选项:

export default defineConfig({
  build: {
    rollupOptions: {
      external: ["node-pty"]
    }
  },
  …
});

相关问题