search
Javascript

Fix: ESM packages need to be imported error

Quick fix for 'ESM packages need to be imported' error. Learn how to properly import ES modules in Node.js and JavaScript environments.

person By Gautam Sharma
calendar_today January 10, 2026
schedule 2 min read
JavaScript ES Modules Node.js Error Fix Module Resolution

The ‘ESM packages need to be imported’ error occurs when trying to require() an ES module package instead of using import(), or when there’s a module system mismatch in your Node.js project.


How the Error Happens

❌ Error Scenario:

// ❌ This causes the error
const somePackage = require('esm-package'); // ❌ ESM packages need to be imported
// Error: ESM packages need to be imported

✅ Quick Fix - Handle ESM Packages Properly

Solution 1: Use Import Instead of Require

// ❌ Wrong way
// const package = require('esm-package');

// ✅ Correct way
import package from 'esm-package';
// OR
import { specificExport } from 'esm-package';

Solution 2: Use Dynamic Import for ESM in CommonJS

// ✅ Use dynamic import in CommonJS files
const package = await import('esm-package');
const actualPackage = package.default;

Solution 3: Configure Package.json for Mixed Modules

// ✅ In package.json, specify module type
{
  "name": "my-app",
  "type": "module",  // ✅ Enables ES modules
  "main": "index.js",
  "exports": {
    "import": "./dist/index.js",
    "require": "./dist/index.cjs"
  }
}

Solution 4: Use CreateRequire for CommonJS Compatibility

// ✅ Use createRequire in ES modules to require CommonJS
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

// ✅ Now you can use require for CommonJS packages
const commonJsPackage = require('commonjs-package');
Gautam Sharma

About Gautam Sharma

Full-stack developer and tech blogger sharing coding tutorials and best practices

Related Articles

Javascript

[SOLVED]: Unexpected token 'export' error

Quick fix for 'Unexpected token export' error. Learn how to resolve ES module syntax issues in Node.js and JavaScript environments.

January 10, 2026
Javascript

How to Fix The requested module does not provide an export named error

Quick fix for 'The requested module does not provide an export named' error. Learn how to properly handle ES module exports and imports.

January 10, 2026
Javascript

Error: Failed to fetch dynamically imported module error

Quick fix for 'Failed to fetch dynamically imported module' error. Learn how to resolve dynamic import issues in JavaScript applications.

January 8, 2026