【问题标题】:'require() of ES modules is not supported. ' error with Node.js, express, swagger-jsdoc'不支持 ES 模块的 require()。 ' Node.js、express、swagger-jsdoc 出错
【发布时间】:2021-06-05 01:59:09
【问题描述】:

我尝试导入 swagger-jsdoc,但出现错误。我在互联网上搜索,但其他解决方案不适合我。

我的 server.js 文件是这样的:

const express = require('express');
const app = express();
const swaggerJsDoc = require('swagger-jsdoc');

const port = 3000;

app.get('/customers', (req,res) => {
    res.send('Customers Route');
})

app.listen(port, ()=> {
    console.log('Server listening on 3000');
})

我的 package.json 文件是这样的:

{
  "name": "swaggertest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.7",
    "swagger-jsdoc": "^7.0.0-rc.4",
    "swagger-ui-express": "^4.1.6"
  }
}

但是当我尝试使用“npm start”运行这个项目时,我收到了这个错误:

节点:内部/模块/cjs/loader:1108 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^

错误 [ERR_REQUIRE_ESM]:必须使用导入来加载 ES 模块: /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js 不支持 ES 模块的 require()。要求()的 /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js 来自 /Users/me/Desktop/Projects/swaggertest/app.js 是一个 ES 模块 文件,因为它是一个 .js 文件,其最近的父 package.json 包含 "type": "module" 将包范围内的所有 .js 文件定义为 ES 模块。而是将 index.js 重命名为以 .cjs 结尾,更改 要求代码使用 import(),或从中删除 "type": "module" /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/package.json。 ... 代码:'ERR_REQUIRE_ESM' ...

我该如何解决这个问题?

【问题讨论】:

  • 哪个版本的节点?那是您实际的整个 package.json 文件吗?具体来说,您的 package.json 中是否定义了 type 字段?顺便说一句,你有什么理由不想使用导入语法?

标签: javascript node.js express ecmascript-6 swagger


【解决方案1】:

我通过将 swagger-jsdoc 降级到 6.0.0 解决了这个问题

所以,我的 package.json 文件现在看起来像:

{
  "name": "swaggertest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.7",
    "swagger-jsdoc": "6.0.0",
    "swagger-ui-express": "^4.1.6"
  }
}

【讨论】:

  • 对我不起作用。还有其他建议吗?
猜你喜欢
  • 2022-11-18
  • 2021-12-28
  • 2022-11-09
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2021-11-01
  • 2022-12-09
  • 2021-10-30
相关资源
最近更新 更多