I want to use LowDB with Electron in plain javascript but i have 'Must use import to load ES Module' error. I did some research but content is so old and doesn't work. this is what i found: https://github.com/typicode/lowdb/issues/169
this is the code i got error:
Javascript
const electron = require("electron");
const { join } = require("path");
const { Low, JSONFile } = require("lowdb"); // this line gives error
const remote =
process.type === "browser" ? electron : require("@electron/remote");
const app = electron.app ? electron.app : remote.app;
const database =
process.env.NODE_ENV === "development"
? join(__dirname, "dev_db.json")
: join(app.getPath("userData"), "todoiva_db.storm");
// Use JSON file for storage
const adapter = new JSONFile(database);
const db = new Low(adapter);
// Read data from JSON file, this will set db.data content
db.read();
The entire error:
App threw an error during load Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/mrocks/others/sipsak/node_modules/lowdb/lib/index.js require() of ES modules is not supported. require() of /Users/mrocks/others/sipsak/node_modules/lowdb/lib/index.js from /Users/mrocks/others/sipsak/database.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/mrocks/others/sipsak/node_modules/lowdb/package.json.
at new NodeError (node:internal/errors:370:5) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1128:13) at Module.load (node:internal/modules/cjs/loader:982:32) at Module._load (node:internal/modules/cjs/loader:823:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13331) at Module.require (node:internal/modules/cjs/loader:1006:19) at require (node:internal/modules/cjs/helpers:93:18) at Object.<anonymous> (/Users/mrocks/others/sipsak/database.js:3:27) at Module._compile (node:internal/modules/cjs/loader:1110:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1140:10)
I just want to use LowDB without ES6.
update: I followed the instructions here but they didn't help in solving my problem.
The new version of lowdb has become pure ESM package, so you can’t use “require”. To use lowdb without ESM, I think the only way is using the older version of lowdb. I have tested the v1.0.0 of lowdb, which can be used by “require” perfectly.
update: please this issue: https://github.com/typicode/lowdb/issues/534