While importing a function from a JavaScript file, many programmers stumbled on an error: “Uncaught SyntaxError: cannot use import statement outside a module”. If you are trying to use import and not inside an ES module, this error may occur. In other words, if you have forgotten to add the type=”module” attribute while loading the script from the folder, this error appears.
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
The Uncaught SyntaxError: cannot use import statement outside a module error can happen in a browser. This error can appear if the src file is written in es6 and not compiled into a standard js file. It is recommended to use the dist folder instead of src. The dist files offer the bundled and compiled JavaScript file.
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
This is our third and last solution. Here, we recommend you to use both import and require statements to load the module. Sometimes, we may have to use both statements to load the module correctly. If you go with this process, you might have significantly less chance of encountering the “cannot use import statement outside a module” error while importing a function from a JavaScript file.
Final Words
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.
Leave a Reply