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!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API