我一直在關注來自 YouTube 的PRN 堆疊教程,并且我開始遇到在索引檔案中為運行 Node v 17.7.2 和 Express 4.17 的服務器應用程式使用 require 函式的問題。
拋出錯誤的代碼在這里:
const express = require("express");
const app = express();
const cors = require("cors");
const routes = require("./routes/jwtAuth")
app.use(express.json());
app.use(cors());
app.use('/auth', myRoutes);
app.get('/', (req, res) =>{
res.send('hello world!');
});
app.listen(process.env.PORT, ()=>
console.log('listening at port 3000'),
);
我得到的錯誤是:
const express = require("express");
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/Nizz0k/Sites/pgpengapi/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
從我讀過的內容來看,這個錯誤曾經僅限于require()在前端代碼中使用,但在 Node v14 之后也可能發生在服務器腳本中。我將型別設定為module. 該錯誤似乎是相對較新的,因為require到目前為止我在應用程式中使用時沒有任何崩潰更改。
uj5u.com熱心網友回復:
當您使用 ES 模塊時(即當您將 type 設定為 時module),您需要使用以下import語法:
import express from 'express';
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447610.html
