How to Fix ESM Import Error in Node.js Quickly
ESM import error in Node.js, ensure your package.json has "type": "module" or use the .mjs file extension. Also, use import syntax only in ES modules, not in CommonJS files.Why This Happens
Node.js supports two module systems: CommonJS and ES Modules (ESM). The import statement is part of ESM and not supported in CommonJS files by default. If your project is not set up for ESM, using import causes an error.
Also, Node.js decides module type by the "type" field in package.json or by file extension (.js for CommonJS by default, .mjs for ESM).
import express from 'express'; const app = express(); app.listen(3000);
The Fix
Add "type": "module" to your package.json to tell Node.js to treat .js files as ES modules. Alternatively, rename your file to .mjs. Then use import syntax freely.
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}
// index.js
import express from 'express';
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});Prevention
Always decide your module system at the start of your project. Use "type": "module" in package.json for ESM or stick to CommonJS with require(). Use consistent file extensions (.js or .mjs) and avoid mixing module types.
Use linters like ESLint with plugins to catch improper import/export usage early.
Related Errors
Other common errors include:
- Cannot find module: Happens if the import path is wrong or the module is missing.
- Unexpected token export: Occurs when trying to run ESM code in CommonJS environment without proper config.
- ReferenceError: require is not defined: Happens if you use
require()in ESM files.