Skip to content
node

How to fix "cannot use import statement outside a module"

Feb 27, 2023Abhishek EH2 Min Read
How to fix "cannot use import statement outside a module"

Have you started working on a Node.js project and got this annoying error?

SyntaxError: Cannot use import statement outside a module

In this article, we will see how to fix it.

Replicating the error

First, create a Node.js project by running npm init -y on an empty folder.

Add the following files to the directory.

utils.js
1const print = message => {
2 console.log(message)
3}
4
5module.exports = { print }
index.js
1import { print } from "./utils.js"
2
3print("hello")

Now if you run node index.js, you will get the above error.

Understanding the issue

Let's first understand why the issue occurs.

You might have used some UI library/framework (say React) and used the same way of importing functions in Node.js as well. Well, this may not work in Node.js by default. Because Node.js uses CommonJS syntax (require syntax) to import other modules/functions. Whereas, the import syntax is called ES modules, which is a standard in JavaScript.

The fix

Now we understand the issue, let's see how to fix it.

Using require syntax

If you cannot modify the file that is being imported (utils.js in our case), then you can opt to use require syntax as follows:

index.js
1const { print } = require("./utils")
2
3print("hello")

Now if you run node index.js, you should see "hello" printed on the terminal.

Using module method

If you have the freedom to change the file being imported, then you can export the function in ES module way and rename the file to have .mjs extension.

utils.mjs
1export const print = message => {
2 console.log(message)
3}

Update the index.js import accordingly

index.js
1import { print } from "./utils.mjs"
2
3print("hello")

Update the package.json with a property called type with the value module.

package.json
1{
2 "name": "cannot-use-import-statement-outside-module",
3 "version": "1.0.0",
4 "description": "",
5 "type": "module",
6 "main": "index.js",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "keywords": [],
11 "author": "",
12 "license": "ISC"
13}

Now if you run the code, it should work fine.

Fixing the error in the browser

If you are getting the error in the browser, then you can update the type attribute to "module" in the script tag:

1<script type="module" src="index.js"></script>

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com