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

# 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"
}


## Get free courses, guided projects, and more

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.

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.

Last Updated: July 15th, 2022