0

I'm building a command line based application and was using require to link various files and node modules. I have previously used Require with no issues and now I get nothing but errors.

Error with Require:

Error [ERR_REQUIRE_ESM]: require() of ES Module ./lib/departments.cjs not supported, Instead change the require of inquirer.js in ./lib/departments.cjs to a dynamic import() which is available in all CommonJS modules.

After this I tried multiple methods to get it to work again, but had no luck so I tried to switch to import. When I switched to import I got this message:

SyntaxError: Cannot use import statement outside a module

Ive tried to add type: "module" to my package.json file, but I don't know if I am putting it in the wrong place or what. My JSON file looks like this

{

  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "directories": {
     "lib": "lib"
},
  "type": "module",
  "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node server.js"
},
  "repository": {
     "type": "git",
     "url": "git+https://.git"
},
 "author": "",
 "license": "MIT",
 "bugs": {
     "url": "https://issues"
},
 "homepage": "https://#readme",
 "dependencies": {
     "console.table": "^0.10.0",
     "dotenv": "^16.0.2",
     "express": "^4.18.1",
     "inquirer": "^9.1.1",
     "mysql2": "^2.3.3",
     "node-fetch": "^2.6.7"
}
  }
dhuw
  • 9
  • 3

1 Answers1

0

Seems like you are using .cjs extension for your js file, cjs is a commonJS file which doesn't support import. You need to use a dynamic import.

It's worth mentioning that ES modules cannot be imported using the require() function of cjs.

Konan
  • 1
  • 1
  • 2
  • Even with the normal .js file naming Im still running into issues with both methods – dhuw Sep 16 '22 at 17:40
  • In the import statement are you calling passing the file extension as well? In some cases you need to pass `import something from './file.js'` instead of `'./file`. – Konan Sep 18 '22 at 11:01
  • ill try switching it around! – dhuw Sep 18 '22 at 19:42