首页 > 解决方案 > 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;

我不知道做错了什么

标签: javascriptnode.jsreactjssyntax-errornode-modules

解决方案


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

export default 

推荐阅读