node.js - lowdb kullanımı ERR_REQUIRE_ESM ile sonuçlanıyor
Node ve Typescript projesinde LowDB kullanmaya çalışıyorum, ama sürekli bana bir ES Modül hatası veriyor...
Hata :
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\{PATH_TO}\node_modules\lowdb\lib\index.js
require() of ES modules is not supported.
require() of C:\{PATH_TO}\node_modules\lowdb\lib\index.js from C:\{PATH_TO}\src\index.ts 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 C:\{PATH_TO}\node_modules\lowdb\package.json.
tsc --init kullanılarak oluşturulmuş bir tsconfig.json kullanıyorum ve bu seçeneklere sahip:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
İşte benim index.ts dosyam, lowdb'den doğrudan kopyalandı. İlginç bir şekilde, sadece JSONFile öğesini ithal ettiğimde bu hatayı veriyor.
import { join } from "path";
import { Low, JSONFile } from "lowdb";
const file = join(__dirname, "db.json");
const adapter = new JSONFile(file);
const db = new Low(adapter);
Bunu çalıştırmak için kullandığım komut nodemon --watch "src/**" --ext "ts,json" --exec "ts-node src/index.ts"
Bütün sabah GitHub sorunlarını okuyorum ve bu sorunu çözmekte bir türlü başarılı olamıyorum.
Bir GitHub deposu oluşturdum, böylece indirebilir ve deneyebilirsiniz.
Node v16.x kullanıyorum. Her türlü yardım için şimdiden teşekkürler!
GÜNCELLEME: Siktir et dedim ve kendi json veritabanımı yazdım...
// lowdb was thorwing errors, so I wrote this one as a stand-in
import path from "path";
import fspromises from "fs/promises";
import fs from "fs";
// path to json file
const FILE_PATH = path.join(__dirname, "database.json");
export const initJSONDatabase = <T>(initialData: T) => {
const read = async () => {
const data = await fspromises.readFile(FILE_PATH, { encoding: "utf-8" });
return JSON.parse(data) as unknown as T;
};
const write = async (data: T) => {
await fspromises.writeFile(FILE_PATH, JSON.stringify(data), {
encoding: "utf-8",
});
};
if (!fs.existsSync(FILE_PATH)) {
write(initialData);
}
return {
read,
write,
};
};
// -- Usage --
//
// const defaultState = {
// users: [],
// posts: []
// };
// const db = initJSONDatabase(defaultState);
// const data = await db.read();
// data.users.push('Jay-Z');
// await db.write(data);
Cevap #1
require() kullanırken node v 12.20.0 ile sorun yaşadım. Node v 12.18.3 kullanıyorum ve,
"dependencies": {
"lowdb": "^1.0.0", //the newest version had the problem
"socket.io": "^3.1.0",
"supervisor": "^0.12.0"
},
ve şimdi çalışıyor!
Cevap #2
"target": "ES2020" ile aynı sorunu yaşıyordum, biri bunu çok iyi çalışan bir şekilde düzeltmiş: https://github.com/typicode/lowdb/issues/471#issuecomment-850908461
