dhuw
dhuw

Reputation: 9

cant get ES modules to work with import or require

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

Upvotes: 0

Views: 1912

Answers (1)

Konan
Konan

Reputation: 1

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.

Upvotes: 0

Related Questions