[英]Swagger-JSdoc is not working on Node.JS 14.15.4 error 'ERR_REQUIRE_ESM'
[英]'require() of ES modules is not supported. ' error with Node.js, express, swagger-jsdoc
我试图导入 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:internal/modules/cjs/loader:1108 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^
错误 [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js 不支持 ES 模块的 require()。 /Users/me/Desktop/Projects/swaggertest/app.js 的 /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/index.js 的 require() 是一个 ES 模块文件,因为它是 a.js file whose nearest parent package.json contains "type": "module" which defines all.js files in that package scope as ES modules. 而是将 index.js 重命名为以 in.cjs 结尾,将需要的代码更改为使用 import(),或者从 /Users/me/Desktop/Projects/swaggertest/node_modules/swagger-jsdoc/package 中删除“type”:“module”。 json。 ...代码:'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"
}
}
这意味着您的库不再支持 require 并且您需要使用 ES 6 语法
import XXX from "node-module";
转到以前的版本可能会有所帮助,但只是暂时的。
为了能够使用导入,您还需要更改 package.json
{
"type": "module",
}
这里有一些学习,从长远来看可能会有所帮助。 https://nodejs.org/api/packages.html#packages_type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.