0

I'm executing a project with node src/main.js from MacOS. Node version 14.5.0 I get on the first line

const express = require('express')
ReferenceError: require is not defined
At ModuleJob.run (internal/modules/esm/module_job.ks:140:23)
at asyns Loader.import (internal/modules/esm/loader.js:162.24)

The strange thing is that if I run the same project( i.e. the same folder from another Mac with same node version), it works fine.

What could that be? What could I do? I tried npm i again, deleted node_modules....out of ideas

package.json

 {
  "type": "module",
  "dependencies": {
  "body-parser": "^1.19.0",
  "express": "^4.17.1",
  "mongodb": "^3.5.9"
 },
 "devDependencies": { "nodemon": "^2.0.4"}
 }

PS. on this particular Mac I had to uninstall/reinstall node a couple of time, swearing a lot. It could be that I have a bad install? if so what can I fix?

Glasnhost
  • 1,023
  • 14
  • 34
  • Does this answer your question? [require is not defined? Node.js](https://stackoverflow.com/questions/31931614/require-is-not-defined-node-js) – ggorlen Sep 21 '22 at 15:14

1 Answers1

0

I had a node v 12.0 on old Mac that was working. I removed "type":"module" from package.json and now it works also on v 14.0 Yuck. require is not defined? Node.js

Glasnhost
  • 1,023
  • 14
  • 34
  • 1
    Yes the thing is, you defined your code as an ES module, so you should use `import` and not `require`. If your code is an ES module you use `import`/`export`, and if it's a CommonJS module you use `require`/`module.exports`. – CherryDT Jul 11 '20 at 16:55