The Error “Uncaught SyntaxError: Cannot use import statement outside a module”, is an error that is invoked when you are using ArcGIS JSAPI 4.12 and trying to import a module. Given below is the snippet of the error you might get:
Uncaught SyntaxError: Cannot use import statement outside a module
I would like to share with you the steps I took to fix the “Uncaught SyntaxError: Cannot use import statement outside a module”
Why “Uncaught SyntaxError Cannot use import statement outside a module” Error is Seen?
The error, “Uncaught SyntaxError: Cannot use import statement outside a module” is seen because might be you have missed to add the type="module"
inside the script tag in your pakage.json file.
You can also face the error if you are currently loading the source file in the src
directory instead of the built file in the dist
directory, this means you are using native modules which do not work.
The detailed solution to fix the error “Uncaught SyntaxError: Cannot use import statement outside a module”, is given below:
How to fix “Uncaught SyntaxError Cannot use import statement outside a module” Error?
To fix the Uncaught SyntaxError Cannot use import statement outside a module error, You will have to add the following type=”module” into your script tag in json file. Also to fix the error, replace the ‘import’ parameter with ‘require’ parameter.
To fix the error, “Uncaught SyntaxError: Cannot use import statement outside a module”, you have to follow one of the below mentioned methods:
Method 1: type==’module’ inside script tag
To fix this error you will have to type="module"
inside the script tag as it is shown below:
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
If you are using Node.js or NPM you will also have to add Add "type": "module"
to your package.json
file as it is given below:
{
// ...
"type": "module",
// ...
}
Please make a note that When you are using modules, if you get ReferenceError: require is not defined
, you’ll need to use the import
syntax rather than require
. You can not natively mix and match between them, so you will either have to pick one or use a bundler if you need to use both.
This should fix the error, “Uncaught SyntaxError: Cannot use import statement outside a module”
Method 2: Replace ‘import’ by ‘require’ parameter
To fix the error in case you are still facing it after following the above method, you will have to replace “import” by “require” as it is shown in the code below:
// import { parse } from 'node-html-parser';
const parse = require('node-html-parser');
This should fix the error, “Uncaught SyntaxError: Cannot use import statement outside a module”
Conclusion
To fix the error “Uncaught SyntaxError: Cannot use import statement outside a module”, You will have to add the following type=”module” in your script tag in your json file. You can also solve your by replacing the ‘import’ with ‘require’.