When are you forgetted to add type=”module” attribute and while loading the script or src file instead of bundled file from the dist folder. Then you will face Uncaught SyntaxError: cannot use import statement outside a module, this error.
In this article, we will discuss about this Uncaught SyntaxError: cannot use import statement outside a module error in Javascript. And how to resolve the error all the possible solutions with examples.
How Uncaught SyntaxError: Cannot use import statement outside a module Error Occurs?
Most of the time you get this error when you are use the ES6 Modules syntax in a script that was not loaded as a module.
Uncaught SyntaxError: Cannot use import statement outside a module
How To Fix Uncaught SyntaxError: Cannot use import statement outside a module Error?
There are different ways to fix Uncaught SyntaxError: Cannot use import statement outside a module this error. Let us take a look at every solution.
- How To Fix Uncaught SyntaxError: Cannot use import statement outside a module Error?
For the solve Uncaught SyntaxError: Cannot use import statement outside a module Error First you have to add type=”module” inside the script tag in your file. The second solution is you have to add “type”: “module” to your package.json file below the command. In some cases, you have to use import by required statements to load the module properly. Below is an example. Now, I hope your error will be solved.
Solution 1: Include type=module
in the script
To solve the error first you have to type=module inside the script tag as given below.
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
Solution 2: Add “type”: “module” in your package.json
The second-way solution is just to add “type”: “module” in your package.json
{
// ...
"type": "module",
// ...
}
If you are using TypeScript, then you have to edit tsconfig.json file and change the module property “commonjs
“, like this below.
// 👇️ ts.config
"target": "esnext",
"module": "esnext",
To
// 👇️ ts.config updated
"target": "esnext",
"module": "commonjs",
Solution 3: replace import by required
You have to use the import and require statement to load the module properly below this example.
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Now you need to use import syntax by require.
// import { parse } from 'node-html-parser';
const parse = require('node-html-parser');
Conclusion
In this article, we have discussed what causes the error and we have discussed ways to fix the error.
we hope this article has been informative. Thank you for reading. Kindly comment and let us know if you found it helpful.