Node.js - Resolve "Cannot use import statement outside a module"

by
Jeremy Canfield |
Updated: July 22 2024
| Node.js articles
This is by far one of the most common errors in Node.js.
Cannot use import statement outside a module
Simply put, there are two types of Node.js.
- CommonJS - uses "require"
- ES Module - uses "import"
If your package.json file has "type": "module" then you are using a module. Otherwise, you are probably using CommonJS.
{
"type":"module",
"dependencies": {
"@aws-sdk/client-sns": "^3.620.0"
}
}
For example, let's say you are trying to use Express.
- FreeKB - Node.js - Getting Started with Client Server on Linux using CommonJS
- FreeKB - Node.js - Getting Started with Client Server on Linux using ES Module
If you are using CommonJS, you would "require" Express.
const express = require("express");
If you are using ES Module, you would "import" Express.
from express import "express";
Did you find this article helpful?
If so, consider buying me a coffee over at