Fixing A JavaScript SyntaxError - Cannot use import statement outside a module Error

Credit where it's due, these are the notes I took straight from this page by Kevin Leary

Node defaults CommonJS.

That means it uses require instead of import.

You'll need to switch to treating code as ECMAScript modules if you want to use import.

You can do that by:

  1. Switching your file extension from .js to .mjs
  2. Add "type": "module" to package.json, or
  3. Run your script with node --input-type module

You can't use both import and require. You'll have to choose one or the other. (NOTE: I'm pretty sure there is a way to use both with a loader in at least React/Next if not vanialla)


More details on modules in node