How to Solve "Cannot use import statement outside a module" Error

Updated onbyAlan Morel
How to Solve "Cannot use import statement outside a module" Error

Table of Contents

  1. Conclusion

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:

BASH
Uncaught 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:

JAVASCRIPT
import { 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.