JavaScript

Cannot Use Import Statement Outside Module in JavaScript

Modules are chunks of JavaScript code written in a file. JavaScript modules facilitate the modularization of code by separating the entire code into modules that can be loaded from anywhere. Modules are used for maintaining, debugging, and reusing code. Every module consists of a piece of code that executes upon loading.

This tutorial will describe:

What is “Cannot Use Import Statement Outside Module” in JavaScript?

The “Cannot use import statement outside a module” is an error in JavaScript that you may face while importing any statement from outside of the module.

How Does “Cannot Use Import Statement Outside Module” Occur in JavaScript?

This error occurs while trying to use ES6 features in a JavaScript project as modules are a newer version included in ES6, in which each module is defined by a unique “.js” file. To import or export classes with their properties, functions, variables, or other components between files and modules, utilize the “import” or “export” statement in a module.

Let’s see how this error occurs in JavaScript:

Example
We have a JavaScript module “data.js” that contains the class “Data” and a method “addData()” that will import in a JavaScript project in a <script> tag using the “import” keyword:

<script>
 import data from 'data.js'
 data.addData();
</script>

The given output shows that while importing the module, the “Cannot use import statement outside a module” error occurs:

Let’s see the solution to fix this error.

How to Fix “Cannot use import statement outside a module” Error in JavaScript?

To fix the “Cannot use import statement outside a module” error, set the type attribute of the <script> tag to the module in HTML code. Now, you can use the syntax of the ES6 module in your JavaScript code:

<script type="module" src="">
 import data from 'data.js'
 data.addData();
</script>

The given window shows that the error has been resolved successfully:

We have compiled the essential information related to the stated error and provided the relevant solution

Conclusion

The “SyntaxError: Cannot use import statement outside a module” occurs when you use the ES6 Modules syntax in a script that was not loaded as a module. To resolve this error and use ES6 module imports in JavaScript, set the type of attribute of the <script> tag to the module in HTML code. This tutorial described what the “cannot use import statement outside a module” error is, how it occurs and how to fix it in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.