我试图导入 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/