vite-plugin / vite-plugin-native

Supports Node/Electron C/C++ native addons
MIT License
10 stars 0 forks source link

Cannot find module './node_natives/@serialport/bindings-cpp.native.cjs' #13

Open kingyue737 opened 1 month ago

kingyue737 commented 1 month ago

I tried this plugin but the built app throw the following error:

Uncaught Exception:
Error: Cannot find module './node_natives/@serialport/bindings-cpp.native.cjs'
Require stack:
D:\release\0.0.1\win-unpacked\resources\app.asar\dist-electron\main...
at Module._resolveFilename (node:internal/modules/cjs/loader: 1 1 52: 15)
at s._resolveFilename (node:electron/js2c/browser_init:2: 121381)
at Module._load
at c._load (node 17025)
at Module.require (node: internal/modules/cjs/loader:1240: 19)
at require 18)
at
at Module._compile (node:internal/modules/cjs/loader: 1373: 14)
at Module._extensions.js (node: internal/modules/cjs/loader:1432: 10)
at Module.load

Platform: Windows

Any help is appreciated

kingyue737 commented 1 month ago

image No file named @serialport/bindings-cpp.native.cjs is generated

kingyue737 commented 1 month ago

I found the cause. My config was native({}). But I just found webpack and forceCopyIfUnbuilt cannot be omitted here while the documentation says that forceCopyIfUnbuilt is true by default.

native({ forceCopyIfUnbuilt: true, webpack: {} })

But now comes another issue, the generated path in bindings-cpp.native.cjs is very strange:

// This is a native module that cannot be built correctly.
module.exports = require("../D:\Solutions\rho-meter\dist-electron\node_natives\node_modules\@serialport\bindings-cpp");

It seems to be a "relative-absolute" path and the backslash \ in the path will cause error on windows.

kingyue737 commented 1 month ago

Found a workaround without this plugin.

  1. Tell Rollup to ignore dynamic require
build: [
      {
        vite: {
          plugins: isDev ? [notBundle()] : undefined,
          build: {
            minify: isProd,
+           commonjsOptions: {
+            ignoreDynamicRequires: true,
+         },
            lib: {
              entry: 'electron/main.ts',
              fileName: 'main',
              formats: ['cjs'],
            },
          },
        },
      },
]
  1. Copy the required .node file to bundle via electron-builder
    {
    "$schema": "node_modules/app-builder-lib/scheme.json",
    "asar": true,
    "directories": {
    "output": "release/${version}"
    },
    "files": [
    "dist-electron",
    ".output/**/*",
    "!node_modules/**/*"
    ],
    "electronLanguages": ["zh-CN"],
    "win": {
    "icon": "dist/favicon.ico",
    +  "files": [
    +    {
    +        "from": "node_modules/@serialport/bindings-cpp/prebuilds/win32-x64",
    +        "to": "prebuilds/win32-x64"
    +    }
    +   ],
    "target": [
      {
        "target": "nsis",
        "arch": ["x64"]
      }
    ]
    },
    }