javascript - ReferenceError:未定义模块
问题描述
所以我一直在尝试运行这个网络应用程序,起初它显示
(node:12960) 警告:要加载 ES 模块,请在 package.json 中设置 "type": "module" 或使用 .mjs 扩展名。
C:\Users\J\react-messenger\stream-chat-boilerplate-api\src\index.js:1
从 'dotenv' 导入 dotenv;^^^^^^
SyntaxError: 不能在模块外使用 import 语句
然后我在 package.json 中设置了 type: module 但它给了我这个错误
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
推荐阅读
- r-markdown - 我可以在 RMarkdown 中引用使用 table1 制作的表格吗?
- python - 寻找关键词
- perl - -s 是否总是在 Perl 中的目录上返回零?
- java - 如何在 Java 中使用 ArrayList 删除不等于对象
- monaco-editor - 如何在自定义令牌提供程序中启用多行匹配
- python - 参数 1 必须是类型,而不是 super() 调用上的 pygame.surface
- ruby - 一次初始化多个对象?
- jquery - 根据选择使用 Fieldset 禁用和隐藏表单元素
- flutter - 为什么我的一种状态在我的测试期间没有被触发
- c++ - SortedVector 没有正确调用函数?