This error can happen in a Node.js or react environment or the browser. There could be several reasons behind this problem. Anyways, we are giving you some helpful solutions to solve the error. Follow our guidelines below.
3 Ways to Fix “Cannot Use Import Statement Outside a Module” Error
- By adding “type”: “module” to the package.json file.
- By adding the type=”module” attribute to the script tag.
- By using both Import and Require statements.
1. By adding “type”: “module” to the package.json file
As already mentioned, this error can occur in Node.js or react applications. So, here’s the solution for Node.js or react environment. You have to ensure that your package.json file has a property “type”: “module”. Once you add the “type”: “module” to the package.json file, it will tell Node you are using the ES module. Thus your problem will be solved.
For a TypeScript user, you need to edit the tsconfig.json file and the module property to “commonjs”. After that, the error will be solved.
2. By adding the type=”module” attribute to the script tag
To solve this error, you must add the type attribute with the value module when you load the script like this – type=”module”. We hope this will help you to fix the error.
3. By using both Import and Require statements
These are the three solutions for the “cannot use import statement outside a module” error. Try these methods, and the error will be solved. If you have any queries about this, please ask in the comment box below.