Fix "cannot use import statement outside a module" in JavaScript/Node

A common error we see, especially among people who are new to JavaScript, is that they try to use the import statement when CommonJS is being used, which only uses the require statement. This results in the error "Uncaught SyntaxError: cannot use import statement outside a module".

If you've run into this error, it's possible that you're having one or more of the following issues:

  • You're using a Node version < 13.2.0
  • You're using Node without the proper package.json settings
  • You're using a browser version that doesn't support ES modules
  • You didn't properly specify the type in your browser <script> tag

This can lead to a lot of confusion, especially if you're new to JavaScript and following someone else's examples without knowledge of the underlying module types.

Node

By default, Node uses CommonJS modules. To fix this in a Node environment, you'll need to edit your package.json file. Specifically, add the following parameter to the file:

{
  "type": "module"
}

As you can probably guess, this will make your project treat the files as ES modules, which allows you to use the import statement. Otherwise you'll need to use the require statement.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Less commonly used is the input parameter --input-type, which is passed to Node via the command line. This can be used to specify the type, which is used like this:

$ node --input-type=module --eval "import { dirname } from 'path'; console.log(path.delimiter);"

Although this is mostly just used when passing strings to Node's eval function via command line, but it's another solution if needed.

Browser

In order to specify the use of modules in the browser, you'll need to pass a parameter to the <script> tag that imports the modules. For example:

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

This feature is supported by current version of all major browser vendors, except for IE 11.

Conclusion

Here we've seen that the "cannot use import statement outside a module" error can occur in JavaScript/Node when attempting to use import statements without properly configuring your project to use a module system.

In this article, we've covered a few solutions for resolving this error, including via the command line or in the package.json file. By using these solutions, you can enable the use of import statements in your code and ensure that your project is properly configured to use a module system.

Last Updated: February 15th, 2023
Was this helpful?
Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms