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
Managing PHP Dependencies with Composer
Getting Started with Svelte
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
How to deploy an Express app using Docker
Getting Started with Sass
Using Push.js to Display Web Browser Notifications
Setting Up a Local Web Server using Node.js
How To Create a Modal Popup Box with CSS and JavaScript
