javascript - '不支持 ES 模块的 require()。 ' Node.js、express、swagger-jsdoc 出错

标签 javascript node.js express ecmascript-6 swagger

我试图导入 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”运行这个项目时,我收到了这个错误:
Node :内部/模块/cjs/loader:1108
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js require() of ES modules is not supported. require() of /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js from /Users/me/Desktop/Projects/swaggertest/app.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/package.json. ... code: 'ERR_REQUIRE_ESM' ...


我该如何解决这个问题?

最佳答案

我通过将 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"
  }
}

关于javascript - '不支持 ES 模块的 require()。 ' Node.js、express、swagger-jsdoc 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66508616/

相关文章:

javascript - 在 .js 文件中使用 ASP.Net 标签?

javascript - 我在网络输入中的正则表达式有什么问题?

node.js - 如何在node.js中调用服务器端的函数

javascript - 是否建议在 Node.js 中使用 cron 作业的子进程?

javascript - Node.js:如何测试函数

javascript - 使用 npm start 启动服务器时出错

javascript - 奇怪的 $.each 行为

javascript - 统计跨站情况下iframe嵌套的层数

javascript - TypeError : Cannot read property 'whenReady' of undefined

javascript - 尝试使用 koa bodyparser 和 ctx.body undefined