JavaScript — How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

JavaScript programs started small by being used here and there. Over time, the usage of JavaScript increased and we’re writing full applications that run in the browser. These large applications can be hard to maintain. It makes sense to think about ways of splitting them up into modules.

Modern browsers ship with native module support allowing them to optimize which module must be loaded.

A common error with modules is the “Uncaught SyntaxError: Cannot use import statement outside a module”. This error means you must explicitly tell the environment that the loaded file is a module. Let’s have a look at how to do that in the browser and Node.js

Node.js Series Overview

Fix “Uncaught SyntaxError” in the Browser

Browsers support modules out of the box. But you must tell the browser that imports using a <script> tag should be handled as a module. For example, frontend tools like Vite create a modern output bundle using modules.

Fix the syntax error by adding type="module" to your script tags:

<script type="module" src="/assets/app.js"></script>  

Fix “Uncaught SyntaxError” in Node.js

You must tell Node.js that you’re using modules when your code is using import or export keywords. Node.js in version 18.x uses CommonJS as the default, but CommonJS doesn’t support these keywords. You must run your app as a module. You can do that by setting the type: "module" of your app inside the package.json file:

package.json

{
  "type": "module"
}

This resolves the “Uncaught SyntaxError” in your Node.js application and you can write modern code using ECMAScript modules.

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.