SyntaxError: Cannot use import statement outside a module
Likely causes
- The script is being executed in Node.js without the package.json file marking it as an ES modulemost likely
- The code is running in a browser without the script tag specifying it as a modulepossible
- A build tool or bundler is not configured to handle ES module syntaxless likely
How to fix it
Check your package.json fileSafe
Open the package.json in your project root and look for a 'type' field. If it is missing or set to 'commonjs', this is often the cause.
Add module type to package.jsonChanges settings
Insert or change the 'type' field to 'module' so Node.js treats .js files as ES modules. This allows import statements.
Edit package.json to include: "type": "module"⚠ Back up your package.json file first as changes can affect how your project runs.
Rename the file to use .mjs extensionChanges settings
Change the file extension from .js to .mjs. This tells Node.js to treat it as a module without changing package.json.
⚠ Back up the file first and update any references to the filename in other code.
If that didn't fix it
The JavaScript file will keep failing to execute until the module configuration is corrected.
When to see a technician
If this error occurs in a complex project with multiple dependencies or you are uncomfortable editing configuration files, consult a software developer.