2

这不是重复的,我已经研究并检查了其他堆栈溢出链接,例如thisthisthis

我像这样在现有的 Node.JS 应用程序中导入了招摇

var swaggerJsdoc = require("swagger-jsdoc"),
var swaggerUi = require("swagger-ui-express");

但错误出现在控制台正在跟踪的 swagger-jsdoc 上

internal/modules/cjs/loader.js:1080 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^

错误 [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\myTestProject\node_modules\swagger-jsdoc\index.js 不支持 ES 模块的 require()。来自 D:\myTestProject\index.js 的 D:\myTestProject\node_modules\swagger-jsdoc\index.js 的 require() 是一个 ES 模块文件,因为它是一个 .js 文件,其最近的父 package.json 包含“类型”: “模块”将包范围内的所有 .js 文件定义为 ES 模块。而是将 D:\myTestProject\node_modules\swagger-jsdoc\index.js 重命名为以 .cjs 结尾,将需要的代码更改为使用 import(),或者从 D:\myTestProject\node_modules\swagger 中删除 "type": "module" -jsdoc\package.json。

at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\myTestProject\index.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14) {   code: 'ERR_REQUIRE_ESM' }
4

1 回答 1

2

我已经尝试了以下步骤,但它们没有用

  1. 在节点启动脚本中添加了标志“--experimental-modules”
  2. npm install esm --save//这也不起作用

But now finally i found a solution which not requires you to rename your .js files to .mjs also it will not require your node to be upgraded if you are alraedy running Node.Js version 12 or above

simply downgrade your swagger-jsdoc to 6.1.0, which is built with CommonJS tools, at first i was using swagger-jsdoc 7.x which was not built using CommonJS tools to downgrade the swagger-jsdoc use the following command of npm

npm install swagger-jsdoc@6.0.1
于 2021-04-10T08:15:22.600 回答