0
0
NodejsDebug / FixBeginner · 4 min read

How to Fix ESM Import Error in Node.js Quickly

To fix the 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).

javascript
import express from 'express';

const app = express();
app.listen(3000);
Output
SyntaxError: Cannot use import statement outside a module
🔧

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.

javascript
{
  "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');
});
Output
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.

Key Takeaways

Add "type": "module" in package.json to enable ES modules in Node.js.
Use .mjs extension or configure package.json to avoid import syntax errors.
Do not mix CommonJS and ES module syntax in the same project files.
Use ESLint to catch module system mistakes early.
Check import paths and module availability to prevent related errors.