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:
- Switching your file extension from
.js
to.mjs
- Add
"type": "module"
topackage.json
, or - 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)