require() 不能在 Express 脚本中使用 Node

require() not working in express script with Node

我一直在关注来自 YouTube 的 PERN stack tutorial,并且我已经开始 运行 遇到在我的服务器应用程序 运行 的索引文件中使用 require 函数的问题带有 Express 4.17 的节点 v 17.7.2。

抛出错误的代码在这里:

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 时没有发生任何崩溃更改。

当你使用ES模块时(即当你设置type为module时),你需要使用import语法:

import express from 'express';