Cannot use import statement outside a module: Why do We Get This Error?
If you got this error, these are the reasons why you got the error:
You will get this error if your node version is older than 13.2.0. So, update your node version. You might get this error if you use Node with incorrect package.json settings. Check your settings before starting the programming.
You will receive this error if your browser doesn’t support Es Modules. For this, always use the latest browser. Lastly, if your <script> tag didn’t specify the type correctly, you will get this error.
These are all the issues that can cause you the error cannot use import statement outside a module. Now, we will know the solution to fix it.
How To Fix cannot use import statement outside a module:
There are two ways to fix this error, one is a browser and the second one is in Nodejs. We will start with the Browser method first.
Fix in Bowser:
Most modern-day browsers support modules, but you must tell the browser to support them. But how to do it? You must use the <script> tag and tell the browser to use it as a module. To fix the error, you must add type= “module” in your script tag.
Example: <script type=”module” src=”./app.js”></script>
This feature is supported by the present version of all major browsers, excluding IE 11.
Fix In Node.Js:
Node.js uses its default modules, so you must tell it that you are using modules by adding import and export statements. To fix the error, you need to edit your package.json file by adding “type”: “module” in your file. By adding this now, you will no longer get the error.
These are the two ways to solve the error cannot use import statement outside a module. Sometimes you must put both import and require commands to load the module correctly.