How to Solve "Cannot use import statement outside a module" Error
Table of Contents
When you use the es6
import statement, you're telling the browser that you want to use the new syntax for importing modules. This is a great way to make your code more readable and easier to maintain.
However, when this is done in a file that's not a module, the browser will throw an error.
In this post, we're going to take a look at the error that occurs when you try to use the import statement in outside of a module.
When you get this error, it looks like this:
BASHUncaught SyntaxError: Cannot use import statement outside a module
This error is thrown because you're trying to use the es6
import statement in a file that the browser is not recognizing as a module.
Let's say we had a file called main.js
and it imports a file called multiply.js
. The code might look like this:
JAVASCRIPTimport { multiply } from "./multiply.js";
console.log(multiply(2, 3));
// 6
This will throw an error because the browser is not recognizing main.js
as a module.
To fix this, we need to add type="module"
to the <script>
tag.
Before the fix:
HTML<script src="main.js"></script>
After the fix:
HTML<script type="module" src="main.js"></script>
Now you should be able to use the import statement in your code since the browser is recognizing main.js
as a module now.
Conclusion
The Cannot use import statement outside a module
is thrown whenever you try to use the es6
import statement in a JavaScript file that has not been marked as a module.
Fixing this error is as easy as adding type="module"
to the <script>
tag, as shown in the example above.
Hopefully, this has fixed the issue for you.
Thanks for reading and happy coding!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Create an RSS Reader in Node
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Setting Up Stylus CSS Preprocessor