When building web applications, you may encounter SyntaxError: Cannot use import statement outside a module error. Here is how to fix it using Node.
This error is potentially raised when using JavaScript or TypeScript in the back-end while developing. However, it could also be encountered client side.
TypeScript Solution
Ensure that you install the latest version of TypeScript, and are using the default tsconfig.json file generated when running tsc init
with the latest version. Also, set up TypeScript correctly for Node and install all necessary packages.
Here is an example Node Express server listening on port 3000 and logging “Hello World!” to the console.
import express from "express"
const app = express()
app.listen("3000", (): void => {
console.log("Hello World!")
// SyntaxError: Cannot use import statement outside a module
})
You may encounter the SyntaxError because of trying to use the import keyword to import a module. In this case, import express from "express"
.
Go to the tsconfig.json file and scroll down to the modules section. You will see a rule like this:
/* Modules */
"module": "esnext"
Replace esnext
with commonjs
.
/* Modules */
"module": "commonjs"
JavaScript Solution
Here is an example Node Express server listening on port 3000 and logging “Hello World!” to the console.
import express from "express"
const app = express()
app.listen("3000", (): void => {
console.log("Hello World!")
// SyntaxError: Cannot use import statement outside a module
})
You may encounter the SyntaxError because of trying to use the import keyword to import a module. In this case, import express from "express"
.
Go to the package.json file and add "type": "module"
. See below for a full example:
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
This allows you to use the import
keyword without receiving an error.
To fix the error on the client side (without frameworks), add the attribute type="module"
to the script tag of the file you wish to import as a module. See below for an example:
<script type="module" src="./add.js"></script>
In conclusion, the SyntaxError: Cannot use import statement outside a module error
occurs primarily when using the import keyword to import modules in Node.js, or when omitting the type="module"
attribute in a script
tag.