In this article, we will resolve the “Uncaught SyntaxError: Cannot use import statement outside a module” error in JavaScript.
The Error “Uncaught SyntaxError: Cannot use import statement outside a module” occurs when we try to use the ES6 Modules syntax in scripts that do not load as a module in Node.
The simple fix to this error is:
- Set the “type” attribute in the script tag to “module“, or
- Set
type = module
in your package.json file.
In JavaScript, when we use the ES6 import and export statement to import a JavaScript file inside another file, we see the following error in your terminal.
For example, when we import a function from math.js inside the main.js file. It throws us an error in our terminal.
main.js
import math from 'math.js'
math.add()
Terminal:
Uncaught SyntaxError: Cannot use import statement outside a module
So to resolve this error, we can try three fixes.
Using package.json in Node
In node, this error can occur when you are trying to use the import statement, and you are not inside an ES module.
So to fix the error, we just need to add a type in the package.json file.
In your package.json file, add "type"="module"
property.
{
"type": "module"
}
Note: we need to set the type property to module in the
package.json
file in order to use the ES6 module imports.
Use type=module in the script section
To fix this error in the HTML code, we just have to add type="module"
as an attribute in the <script>
element of main.js. This declares the script as a module instead of a normal JS file.
<script type="module" src="main.js"></script>
The script ( in this case main.js ) into which we import the modules acts as a top-level module.
You can also embed the module script in your HTML file , just place the import module scripts in the body inside the <script>
element.
<body>
<script type="module">
/* JavaScript module code here */
</script>
</body>
If you don’t use the type="module"
, in firefox browser it will show SyntaxError: import declarations may only appear at top level of a module error.
For node.js / NPM
If you are using a node application and want to use the import statement, then you will also get the “Cannot use import statement outside a module” error. It is because ES6 import and export statements are not supported in node by default.
In node 9, you have to use type="module"
inside your package.json file, use .mjs extension, and then enable --experimental-modules
flag and run:
node --experimental-modules main.js
Read the full article on How to use es6 import statements in Node.js, if you are using node 12 or greater.
Troubleshoot : In node 9, if you get the “ReferenceError: require is not defined” error, just use import syntax instead of require. You cannot use both import and require in your nodejs application. You have to pick one.
Related Topics:
(Resolved) npm ERR! missing script: start in Node.js application
Resolve – Node Unexpected Token Import Error