The occurrence of this error can vary depending on whether you’re dealing with JavaScript on the server-side using Node.js or on the client-side within a web browser. The error “Cannot use import statement outside a module” stems from several potential causes, with the appropriate solution hinging on how you incorporate modules or script tags into your code.
Add type="module" inside the script tag
When working with ECMAScript modules and JavaScript module import statements in the browser, you’ll need to explicitly tell the browser that a script is module. To do this, you have to add type=“module” onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.
<script type="module" src="./index.js"></script>
If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property “type”: “module” as shown below.
{
// ...
"type": "module",
// ...
}