Ricerca nel sito web

node.js - L'utilizzo di lowdb provoca ERR_REQUIRE_ESM


Sto cercando di usare LowDB in un progetto Node e Typescript, ma continua a darmi un errore di modulo ES...

Errore :

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.

Sto usando un tsconfig.json che è stato generato usando tsc --init e ha queste opzioni:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Ecco il mio index.ts, copiato direttamente da lowdb. Curiosamente, genera questo errore solo quando importo JSONFile.

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);

Il comando che uso per eseguire questo è nodemon --watch "src/**" --ext "ts,json" --exec "ts-node src/index.ts"

Ho passato tutta la mattina a leggere i problemi su GitHub e non riesco a capire questo problema.

Ho creato un repository GitHub, così puoi scaricarlo e provarlo.

Sono su Node v16.x. Grazie in anticipo per qualsiasi aiuto!

MODIFICA: Ho detto al diavolo, e ho scritto il mio database json...

// 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); 

Risposta n. 1

Ho avuto il problema con l'uso di require() con node v 12.20.0. Uso node v 12.18.3 e,

 "dependencies": {
    "lowdb": "^1.0.0", //the newest version had the problem
    "socket.io": "^3.1.0",
    "supervisor": "^0.12.0"
  },

e ora funziona!

Risposta n. 2

Stavo riscontrando lo stesso problema con "target": "ES2020", qualcuno ha già fatto una correzione che per me funziona perfettamente: https://github.com/typicode/lowdb/issues/471#issuecomment-850908461

Articoli correlati