簡體   English   中英

'不支持 ES 模塊的 require()。 ' Node.js、快遞、swagger-jsdoc 出錯

[英]'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM