ReferenceError:未定义模块



所以我一直在尝试运行这个web应用程序,起初它显示

(节点:12960(警告:要加载ES模块,请设置";类型":"模块";在package.json中,或者使用.mjs扩展名
C:\Users\J\areact messenger\stream chat样板文件api\src\index.js:1
从"dotenv"导入dotenv;^^^^^^

SyntaxError:无法在模块之外使用导入语句

然后我把type:module放在package.json中,但它给了我这个错误

ReferenceError:模块未定义

at file:///C:/Users/J/react-messenger/stream-chat-boilerplate-api/src/index.js:38:1

这是我的代码:

import dotenv from 'dotenv';
dotenv.config();
import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
const api = express();
api.use(cors());
api.use(compression());
api.use(helmet());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(bodyParser.json());
api.listen(process.env.PORT, error => {
if (error) {
console.warn(error);
process.exit(1);
}
// eslint-disable-next-line array-callback-return
fs.readdirSync(path.join(__dirname, 'routes')).map(file => {
require('./routes/' + file)(api);
});
console.info(
`Running on port ${process.env.PORT} in ${
process.env.NODE_ENV
} mode. 🚀`
);
});
module.exports = api;

我不知道做错了什么

您将ES导入与CommonJS混合在一起——在文件底部有module.exports = api;,这是CJS术语。ES模块等效为:

export default api

最新更新