【问题标题】:ReferenceError: module is not definedReferenceError:未定义模块
【发布时间】:2021-01-06 12:58:17
【问题描述】:

所以我一直在尝试运行这个网络应用程序,一开始它显示了

(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;

我不知道自己做错了什么

【问题讨论】:

  • 正如它所说:在 package.json 中设置 "type": "module" 或使用 .mjs 扩展名。

标签: javascript node.js reactjs syntax-error node-modules


【解决方案1】:

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

export default 

【讨论】:

    【解决方案2】:

    检查 package.json 中的 dotenv,确保 npm install dotenv。 https://www.npmjs.com/package/dotenv

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2016-02-28
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多