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

November - 2021

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.

More details on modules in node