我有這個代碼,應該可以正常作業:
import express from "express";
import nunjucks from "nunjucks";
import fetch from "node-fetch";
const app = express();
app.use(express.static("public"));
nunjucks.configure("views", {
autoescape: true,
express: app,
});
app.set("view engine", "njk");
app.get("/", (req, response) => {
fetch("https://swapi.dev/api/")
.then((response) => response.json())
.then((data) =>
console.log(data)
// response.render("home", { categories: data }
)
});
app.listen(3000, () => {
console.log("Server started on http://localhost:3000");
});
但是當我嘗試運行它時ts-node src/index.ts,我有這個錯誤:
Error [ERR_REQUIRE_ESM]: require() of ES Module /mnt/c/Users/me/Desktop/CODE/sw-api/node_modules/node-fetch/src/index.js from /mnt/c/Users/me/Desktop/CODE/sw-api/src/index.ts not supported.
Instead change the require of index.js in /mnt/c/Users/me/Desktop/CODE/sw-api/src/index.ts to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/mnt/c/Users/me/Desktop/CODE/sw-api/src/index.ts:9:36)
at Module.m._compile (/mnt/c/Users/me/Desktop/CODE/sw-api/node_modules/ts-node/dist/index.js:735:29)
at Object.require.extensions.<computed> [as .ts] (/mnt/c/Users/me/Desktop/CODE/sw-api/node_modules/ts-node/dist/index.js:737:16)
at main (/mnt/c/Users/me/Desktop/CODE/sw-api/node_modules/ts-node/dist/bin.js:238:16)
at Object.<anonymous> (/mnt/c/Users/me/Desktop/CODE/sw-api/node_modules/ts-node/dist/bin.js:351:5) {
code: 'ERR_REQUIRE_ESM'
}
我不太明白,因為我不使用 require() 來匯入我的模塊
誰能幫助我?謝謝
uj5u.com熱心網友回復:
如果還沒有,請嘗試package.json使用"type": "module". 另請查看以下內容:Error: require() of ES modules is not supported when importing node-fetch和Error [ERR_REQUIRE_ESM]: require() of ES Module not supported。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447615.html
