'require() of ES modules is not supported. ' error with Node.js, express, swagger-jsdoc

23,512

I solved this issue with downgrade swagger-jsdoc to 6.0.0

So, my package.json file now look like:

{
  "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"
  }
}
Share:
23,512
akasaa
Author by

akasaa

Updated on July 09, 2022

Comments

  • akasaa
    akasaa almost 2 years

    I trying to import swagger-jsdoc but I get an error. I searched on internet but other solutions not work for me.

    My server.js file like that:

    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');
    })
    

    And my package.json file like that:

    {
      "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"
      }
    }
    

    But when I try to run this project with "npm start" I getting this error:

    node:internal/modules/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' ...

    How can I solve this issue?