. Advertisement .
..3..
. Advertisement .
..4..
Hello everyone, today we will learn about a new problem. Have you encountered this error “Uncaught SyntaxError: Cannot use import statement outside a module” in the process of working? Do you find it difficult to handle them? Don’t worry, the following article will help you find the solution quickly!
When does it occur?
This error will appear when you want to add milsymbol.js to the program. The error displayed is as follows:
Uncaught SyntaxError: Cannot use import statement outside a module
What causes error?
There are several possible causes for the “Uncaught SyntaxError: Cannot use import statement outside a module” error:
– in your script was forgotten tag type=”module”
– Your native code is being set unaltered/unbundled state
– ES6 compiler not installed
How to fix error “Uncaught SyntaxError: Cannot use import statement outside a module”
In this article, we will give you some solutions to fix the error. Each solution will have a different level of complexity. So you can absolutely choose the option that best suits you.
Solution 1:
This way will involve script tag. It’s very simple, you just need to add the word “module” to the tag as follows:
<script type="module" src="../src/myscript.js"></script>
If you have tried both of the above options and it doesn’t work, try adjusting this command line:
<script src="../src/myscript.js"></script>
becomes:
<script type="module" src="../src/myscript.js"></script>
Solution 2:
Install the following 2 versions in your tsconfig.json:
"lib": [
"es2020",
"dom"
]
with
"lib": [
"es2016",
"dom"
]
Or run the following code in index.html
<script type="module">
import { ms } from "./ms.js";
import Symbol from "./ms/symbol.js";
</script>
Solution 3
Go to your package.json folder and add the line “type”: “module” like below:
{
// do something ...
"type": "module",
// do something ...
}
Note that you can only apply syntax input when ReferenceError: require is not defined appears, if you want to apply both syntax input and request, you must use a bundler to support it.
Solution 4:
For the ECMAScript 6 version used in the browser, go to the .js extension file, then add type=”module” at the script tag.
Otherwise, if you’re on Node.js, access to the .mjs extension then run the following command:
node --experimental-modules filename.mjs
Solution 5:
Next up is a quick fix. You just need to convert “import” to “require” and the error is fixed
// import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Conclusion
To summarize, above we have introduced to you 4 simple ways to fix the error “Uncaught SyntaxError: Cannot use import statement outside a module” when importing ECMAScript 6. If you have any problems or questions, you can contact us immediately to find a solution. Thanks for reading!
Leave a comment