How to fix the "Cannot Use Import Statement Outside a Module" error in JavaScript

#archive

This post is out of date

This post has been migrated from my old blog. It may have broken links, or missing content.

The common JavaScript error “Cannot use import statement outside a module” indicates issues in importing modules and occurs in non-ECMAScript Module (ESM). Here’s a quick solution for both Browser and Node.js (sometimes referred to as “server-side JavaScript”) environments.

Browser

Ensure your JavaScript code runs in ESM by using the module type script tag:

<!-- Before -->
<script src="your-file.js"></script>
<!-- After -->
<script type="module" src="your-file.js"></script>

If you have concerns about whether your users’ browsers support the type="module" directive, check out the “JavaScript modules via script tag” page on Can I use.

Node.js / server-side

There are two key ways to resolve this error.

Updating the file extension

Try changing the ‘.js’ extension to ‘.mjs’: Node.js treats ‘.mjs’ as ES modules.

Terminal window
$ mv server.js server.mjs

If that doesn’t work, you can modify the project’s package.json. Include "type": "module" to your package.json to interpret ‘.js’ files as ES modules.

{
"type": "module"
}

If you don’t have a package.json for your project, run npm init -y to create one first.