TJB*_*man 6 node.js typescript lowdb
我正在尝试在 Node 和 Typescript 项目中使用LowDB,但它一直给我一个 ES 模块错误...
错误:
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.
Run Code Online (Sandbox Code Playgroud)
我使用的是使用tsconfig.json生成的tsc --init,它具有以下选项:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的index.ts,直接从lowdb复制过来的。有趣的是,它只在我 import 时抛出这个错误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);
Run Code Online (Sandbox Code Playgroud)
我用来运行它的命令是 nodemon --watch "src/**" --ext "ts,json" --exec "ts-node src/index.ts"
我整个上午都在阅读 GitHub 问题,但我似乎无法弄清楚这个问题。
我做了一个GitHub Repo,所以你可以下载并试用它。
我在 Node v16.x 上。在此先感谢您的帮助!
编辑: 我说 F-it,并编写了我自己的 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);
Run Code Online (Sandbox Code Playgroud)
小智 2
我在使用节点 v 12.20.0require()时遇到问题。我使用节点v 12.18.3并且,
"dependencies": {
"lowdb": "^1.0.0", //the newest version had the problem
"socket.io": "^3.1.0",
"supervisor": "^0.12.0"
},
Run Code Online (Sandbox Code Playgroud)
现在它正在工作了!
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |