Sometimes, we want to fix Uncaught SyntaxError: Unexpected token import error when importing JavaScript modules in the browser.
In this article, we’ll look at how to fix Uncaught SyntaxError: Unexpected token import error when importing JavaScript modules in the browser.
How to fix Uncaught SyntaxError: Unexpected token import error when importing JavaScript modules in the browser?
To fix Uncaught SyntaxError: Unexpected token import error when importing JavaScript modules in the browser, we can set the script element’s type
attribute to module
.
For instance, we write
calc.js
const sum = (a, b) => {
return a + b;
};
export { sum };
to create the calc.js module.
Then we write
<script type="module">
import { sum } from "./calc.js";
console.log(sum(2, 3));
</script>
to import the sum
function we exported from calc.js in the script tag.
We set the type
attribute to module
to let the browser know that we can import and export values in the script element.
Conclusion
To fix Uncaught SyntaxError: Unexpected token import error when importing JavaScript modules in the browser, we can set the script element’s type
attribute to module
.