SyntaxError: Cannot use import statement outside a module
Add type="module" inside the script tag
Add "type": "module" to your package.json
If you are developing Node.js or React applications and utilizing import statements instead of require to import modules, make sure your package.json file includes the property "type": "module" as illustrated below:
This declaration enables ECMAScript modules to be used effectively in your project, allowing seamless integration of import statements.
Use the extension .mjs in your files
When working within a Node.js application and endeavoring to utilize import statements, encountering the "Cannot use import statement outside a module" error is probable. This occurs due to the default lack of support for ES6 import and export statements within Node.js. To address this issue, it's recommended to utilize the .mjs file extension for your modules and subsequently employ the command designed for running such files. By adhering to this approach, you can effectively resolve the encountered error and enable the seamless utilization of import statements in your Node.js environment.
Use import by required
In some cases, you may have to use both import and require statements to load the module properly.
The "SyntaxError: Cannot use import statement outside a module" error typically arises when attempting to use the import statement outside of an ES6 module context, whether in a browser or Node.js environment. This issue can be resolved by ensuring your environment supports modules, utilizing the appropriate file extensions (.mjs for Node.js), and potentially employing module bundlers like Webpack for compatibility with older environments.