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
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Create an RSS Reader in Node
Getting Started with Electron
Best Visual Studio Code Extensions for 2022
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 Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
