Skip to content

How to fix Syntaxerror: Cannot use import statement outside a module?

  • by
  • 2 min read
What is Metadata? Types and benefits | Candid.Technology

Web development has become a lot easier thanks to the many design and backend frameworks available for developers to play around with and come up with better-looking and performing websites. That said, the coding part can still throw a rut in your workflow. 

In this article, we’re talking about the “Syntaxerror: Cannot use import statement outside a module” error, its causes and what you can do to fix the problem.

Also read: How to fix Javascript error: ipython is not defined?


What causes this error?

The error occurs exactly because of what it states the reason is — you’re trying to use import outside of an ES module. This can happen both in a Node.js environment and in the browser. 

Top 7 games for kids to learn coding | Candid.Technology

Also read: How to remove first element from array in Python?


How to fix this?

Here are two fixes you can try out.

For Node.js environments

If you’re working with a Node framework, the simplest solution is to add the module type to your package file. Simply find the package.json file and add the following snippet.

{
  "type": "module"
}

Now restart your Node.js server, and you should be good to go. 


For web browser environments

If you’re writing HTML code for browsers, include type=module wherever you import your JavaScript file. 

<script type="module" src="./JavaScriptFile.js"></script>

Refresh the page, and the error should be gone.

Also read: How to fix scroll not working in VIM Linux?

nv-author-image

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>