The Uncaught syntaxerror: cannot use import statement outside a module occurs if you have forgotten to add type="module"
attribute while loading the script or if you are loading the src file instead of bundled file from the dist folder.
There are several reasons behind this error, and the solution depends on how we call the module or script tag. We will look at each of the scenarios and the solution with examples.
How to fix cannot use import statement outside a module error?
Solution 1 – Add “type”: “module” to package.json
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.
Adding “type”: “module” to package.json will tell Node you are using ES2015 modules(es modules), which should get solve the error.
{
// ...
"type": "module",
// ...
}
If you are using TypeScript, we need to edit the tsconfig.json file and change the module property to “commonjs
“, as shown below.
ts.config file
Change the ts.config file as shown below to resolve the Uncaught syntaxerror: cannot use import statement outside a module error.
ts.config
"target": "esnext",
"module": "esnext",
to
ts.config updated
"target": "esnext",
"module": "commonjs",
Solution 2 – Add type=”module” attribute to the script tag
Another reason we get this error is if we are loading the script from the src directory instead of the built file inside the dist directory.
It can happen if the src file is written in es6 and not compiled into a standard js file. The dist files usually will have the bundled and compiled JavaScript file, and hence it is recommended to use the dist folder instead of src.
We can solve this error by adding a simple attribute type="module"
to the script, as shown below.
<script type="module" src="some_script.js"></script>
Solution 3 – Use import and require to load the modules
In some cases, we may have to use both import and require statements to load the module properly.
For Example –
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Note: When using modules, if you get ReferenceError: require is not defined
, you’ll need to use the import
syntax instead of require
.