VIteJS Import native compiled node module fails 'Unexpected character'
Asked Answered
S

1

8

I am trying to transition an electron application built with create-react-app to ViteJS. So far, I've managed to get a lot of things fixed, but I'am having an issue with one of our dependencies.

My project uses an internal library built in golang for performance reasons, and this library is called from the main process of the electron application. However, I get the following error when running vite build.

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

This happens with the following line

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

goapi.node is the compiled library. This library is compiled using node-gyp, and I'm 100% sure that the compilation is right, because it is working with the current setup that uses create-react-app.

Is there a plugin to add in the vite config to support importing native modules? If not, how can I get around this problem?

Siddon answered 16/12, 2022 at 20:49 Comment(0)
M
4

I had a similar problem adding node-pty to a project based on Electron Forge's Vite + TypeScript template.

My solution was to mark node-pty as external in the Rollup configuration, which tells Rollup to keep that module external to the bundle.

In my "vite.main.config.ts" file (which is exclusively for compiling the Electron main process), I added a "build" section to "defineConfig" to define this Rollup option:

export default defineConfig({
  build: {
    rollupOptions: {
      external: ["node-pty"]
    }
  },
  …
});
Mcnabb answered 30/8, 2023 at 22:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.