caoxiemeihao / nuxt-electron

Integrate Nuxt and Electron
MIT License
191 stars 21 forks source link

Could not dynamically require "x.node" #58

Closed Ak1r0 closed 10 months ago

Ak1r0 commented 1 year ago

Hi !

I've just upgrade from v4.5 to v5 and got this error when starting the app in dev mode (with nuxt dev cmd) : "Could not dynamically require "better_sqlite3.node" when upgrading from v4.5 to v5 (same error with v6). Reversing to v4.5 resolve the error.

Any idea about the problem ?

Error details :

App threw an error during load
Error: Could not dynamically require "app\build\better_sqlite3.node". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.
    at Kc (app\dist-electron\main.js:18:2434)
    at F (app\dist-electron\main.js:18:5392)
    at new Ka (app\dist-electron\main.js:20:12962)
    at Object.<anonymous> (app\dist-electron\main.js:20:14140)
    at Module._compile (node:internal/modules/cjs/loader:1241:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1296:10)
    at Module.load (node:internal/modules/cjs/loader:1096:32)
    at Module._load (node:internal/modules/cjs/loader:937:12)
    at f._load (node:electron/js2c/asar_bundle:2:13330)
    at loadApplicationPackage (app\node_modules\.pnpm\electron@24.3.1\node_modules\electron\dist\resources\default_app.asar\main.js:121:16)

The error is thrown by the new Database() call in this code :


import {app} from "electron";
import path from "path";
import Database from 'better-sqlite3';

declare global {
    var db: typeof Database
}

const isProduction = app.isPackaged

const dbPath = isProduction
    ? path.join(app.getPath('userData'), process.env.DATABASE_URL!)
    : path.join('./database', process.env.DATABASE_URL!)

const extDir = path.join('../../database', 'ext')
export const db = global.db ?? new Database(dbPath, { verbose: console.log })
yejimeiming commented 10 months ago

Perhaps you can try the fllowing way:

import { createRequire } from 'node:module';

const Database = createRequire(import.meta.url)('better-sqlite3');
Ak1r0 commented 10 months ago

Perhaps you can try the fllowing way:

import { createRequire } from 'node:module';

const Database = createRequire(import.meta.url)('better-sqlite3');

Thanks for your answer ! But tbh by the time i did change a lot a things... Like call new Database in a function executed at very first usage. I figured out I had conception mistakes with the previous code. The new Database call was done even before Electron app was ready.

Then with your answer i tried to reproduce and updated every package to last version +changes few things in nuxt.config.ts and electron-builder.json5 and now it's all working for me. Still I didn't really understand what was wrong...