All articles
Node.jsJavaScriptESMTypeScript

Node.js ESM vs CommonJS Errors: Causes and Fixes

Cannot use import statement, require is not defined, ERR_REQUIRE_ESM and more: why each Node.js ESM/CommonJS error happens and the exact fix.

Tushar Pachouri16 min read

Node.js runs two module systems side by side: CommonJS (require, module.exports) and ES modules (import, export). Almost every confusing error you hit when mixing them comes from one decision Node makes before running a single line of your code: which system does this file belong to? Once you know how Node makes that call, each error below has an obvious fix.

TL;DR

  • .mjs is always ESM, .cjs is always CommonJS, and .js follows the "type" field of the nearest package.json (CommonJS when it is missing, though recent Node reparses files with ESM syntax as ESM and warns).
  • ESM has no require, exports, __dirname or __filename. Use import, createRequire, and import.meta.dirname (or fileURLToPath(import.meta.url) on older Node).
  • Relative ESM imports need the full file name. In TypeScript with NodeNext, write ./utils.js even though the file on disk is utils.ts.
  • Never pass a raw absolute path to import(). Convert it with pathToFileURL(p).href, or Windows fails with a c: protocol error.
  • Recent Node versions can require() ES modules without top-level await and can run .ts files directly. Check node --version before trusting an old answer.

Note: All output in this article was captured on Node 24 on Windows; paths are shortened, and stack traces and some follow-up hint lines are trimmed.

How Node decides a file's module type

Before anything runs, Node classifies the file:

FileNearest package.jsonLoaded as
.mjs or .mtsanythingES module
.cjs or .ctsanythingCommonJS
.js or .ts"type": "module"ES module
.js or .ts"type": "commonjs"CommonJS
.js or .tsno type fieldCommonJS, with syntax detection in recent versions

The .ts, .mts and .cts rows apply only on Node versions with built-in type stripping (see the .ts section below); elsewhere you need tsx or a compile step.

"Nearest" means Node walks up from the file's folder and stops at the first package.json it finds, even one that contains nothing but a type field. That is handy: a two-line package.json inside dist changes how every file in that folder loads.

Node stops at the first package.json above a file, so the one in dist overrides the root.

The last row has changed over time. Older Node versions threw on the first import in a typeless .js file. Recent versions (syntax detection became the default during the Node 22 line and was backported to later 20.x releases; check the notes for your version) try CommonJS first, then reparse a file with ESM syntax as ESM and warn:

Text
(node:33612) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///C:/projects/app/index.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to C:\projects\app\package.json.

Treat that warning as a to-do item. Set type explicitly so your code does not depend on a guess.

The exports field and its conditions

The exports field in a package's package.json controls which files consumers can reach and which file each kind of consumer gets. Conditions let one package hand an ESM build to import and a CommonJS build to require:

JSON
{
  "name": "tiny-id",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "import": {
        "types": "./dist/index.d.ts",
        "default": "./dist/index.js"
      },
      "require": {
        "types": "./dist/index.d.cts",
        "default": "./dist/index.cjs"
      }
    },
    "./package.json": "./package.json"
  }
}

Each build needs its own declaration file, .d.ts for ESM and .d.cts for CommonJS; one shared .d.ts in a "type": "module" package gives CommonJS consumers ESM-flavoured types. Both Node and TypeScript match conditions in key order. Node ignores types, but TypeScript stops at the first match, so put types first. A default condition must always come last.

Once exports exists it is also an allow-list: a deep import such as tiny-id/dist/index.js fails with ERR_PACKAGE_PATH_NOT_EXPORTED. That is why the example exports ./package.json explicitly.

tiny-id, like counter-dual, slugify-esm and legacy-strings below, is a small stand-in package I created under node_modules for these demos, not something to install from npm.

The dual package hazard

Shipping two builds has a cost. If one part of an app imports the package and another requires it, Node loads two separate copies, and any module-level state (caches, singletons, instanceof checks against exported classes) splits in two. counter-dual maps import to dist/index.js and require to dist/index.cjs. The ESM build:

JavaScript
let count = 0;

export const increment = () => ++count;

The CommonJS build keeps its own counter:

JavaScript
let count = 0;

module.exports = { increment: () => ++count };

An app that reaches it both ways:

JavaScript
import { createRequire } from "node:module";
import { increment as incrementEsm } from "counter-dual";

const require = createRequire(import.meta.url);
const { increment: incrementCjs } = require("counter-dual");

console.log(incrementEsm(), incrementEsm());
console.log(incrementCjs());
Text
1 2
1

The CommonJS copy is a separate instance, so it starts from zero. For anything stateful, keep one real implementation and make the other entry point a thin wrapper, or ship ESM only.

ONE PACKAGE, TWO MODULE INSTANCES your app import + require import require dist/index.js dist/index.cjs ESM build CommonJS build count = 2 count = 1 incrementEsm() twice separate copy, from 0 Output: 1 2, then 1. Module-level state splits in two.
Importing and requiring the same dual package loads two copies with separate state.

Top-level await is ESM-only

ES modules can await at the top level because the ESM loader can wait on an asynchronous module graph. require() is synchronous, so CommonJS cannot. A .cjs file like this fails to parse:

JavaScript
const { readFile } = require("node:fs/promises");

const text = await readFile(__filename, "utf8");
console.log(text.length);
Text
SyntaxError: await is only valid in async functions and the top level bodies of modules

Wrap the code in an async function main(), or move the file to ESM. Remember this rule for the require() section below.

Cannot use import statement outside a module

Text
(node:21396) Warning: Failed to load the ES module: C:\projects\app\index.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module

Cause: Node loaded the file as CommonJS, which does not understand import. You get this when the file is .cjs, when the nearest package.json says "type": "commonjs", or on older Node versions without syntax detection. Test runners and tools that push files through their own CommonJS pipeline can produce it too.

JSON
{
  "name": "my-app",
  "type": "commonjs"
}
JavaScript
import path from "node:path";

console.log(path.join("a", "b"));

Fix: tell Node the file is ESM. Change the type for the whole package:

Diff
 {
   "name": "my-app",
-  "type": "commonjs"
+  "type": "module"
 }

Or rename just this file to .mjs and leave the rest of the package alone. If the project is CommonJS on purpose, write const path = require("node:path") instead.

require is not defined in ES module scope

Text
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\projects\app\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Cause: the file is ESM, where require does not exist. It shows up after adding "type": "module" to an older project, or in a typeless package where syntax detection spotted an import somewhere in the file and switched the whole file to ESM.

JavaScript
const fs = require("node:fs");

console.log(typeof fs.readFileSync);

Fix: use import fs from "node:fs". When you genuinely need require inside ESM, for example to reach a CommonJS-only API such as require.resolve, build one:

JavaScript
import { createRequire } from "node:module";

const require = createRequire(import.meta.url);
const pkg = require("./package.json");

console.log(pkg.name);

require() of ES Module not supported

Text
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\projects\app\node_modules\slugify-esm\index.js from C:\projects\app\index.cjs not supported.
Instead change the require of index.js in C:\projects\app\index.cjs to a dynamic import() which is available in all CommonJS modules.

Cause: CommonJS code called require() on a package that only ships ESM. This became common when popular packages went ESM-only. slugify-esm stands in for any ESM-only package with a default export: "type": "module", "exports": "./index.js", and a one-line export default function in index.js.

JavaScript
const slugify = require("slugify-esm");

console.log(slugify("Hello ESM World"));

Fix 1: dynamic import(). It works from CommonJS in every supported Node version. It returns a promise, so the call site becomes async:

JavaScript
async function main() {
  const { default: slugify } = await import("slugify-esm");
  console.log(slugify("Hello ESM World"));
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});

Fix 2: upgrade Node. Recent releases can require() synchronous ES modules by default. Support was switched on around Node 22 and 23 and backported to later 20.x releases, so check the changelog for your exact version. On Node 24, I had to pass --no-experimental-require-module to reproduce the error above. Three catches:

  • require() returns the module namespace object, so a default export lives on .default. On Node 24 the broken snippet above does not throw ERR_REQUIRE_ESM at all; it throws TypeError: slugify is not a function. Write const { default: slugify } = require("slugify-esm").
  • If the package's exports map has only an import condition (no require or default), require() still fails, with ERR_PACKAGE_PATH_NOT_EXPORTED (No "exports" main defined). Use import() or move the caller to ESM.
  • If anything in the required graph uses top-level await, you get a different error and must fall back to import():
Text
Error [ERR_REQUIRE_ASYNC_MODULE]: require() cannot be used on an ESM graph with top-level await. Use import() instead. To see where the top-level await comes from, use --experimental-print-required-tla.

Fix 3: switch the caller to ESM. If you own the calling code, converting it removes the problem for good.

Missing dirname and filename in ESM

Text
ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'C:\projects\app\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Cause: __dirname, __filename, require, module and exports were never true globals. Node passes them in through a wrapper function it puts around every CommonJS file. ES modules have no wrapper.

COMMONJS FILE ES MODULE (function (exports, require, module, __filename, __dirname) { }) your code __dirname works no wrapper function your code __dirname is not defined use import.meta.dirname
CommonJS gets its module variables from a wrapper function that ES modules do not have.
JavaScript
import path from "node:path";

const templates = path.join(__dirname, "templates");
console.log(templates);

Fix on recent Node: use import.meta.dirname and import.meta.filename. They arrived around Node 20.11 and 21.2, so check your version:

JavaScript
import path from "node:path";

const templates = path.join(import.meta.dirname, "templates");
console.log(templates);

Portable fix for older versions:

JavaScript
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

console.log(path.join(__dirname, "templates"));

Avoid new URL(import.meta.url).pathname as a shortcut. On Windows it returns /C:/... with a leading slash, and spaces come back as %20.

Cannot find module on relative imports

Text
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\projects\app\src\utils' imported from C:\projects\app\src\index.js

Cause: CommonJS tries utils, utils.js, utils.json, utils/index.js and more. ESM does no guessing. A relative specifier is a URL, and it must point at the exact file. Directory imports such as ./lib fail too, with ERR_UNSUPPORTED_DIR_IMPORT.

Diff
-import { add } from "./utils";
+import { add } from "./utils.js";

TypeScript with NodeNext

By default TypeScript does not rewrite import paths when it compiles. With "module": "NodeNext" and "moduleResolution": "NodeNext", the compiler enforces the ESM rule at type-check time, and you write the extension of the output file:

Text
src/index.ts(1,21): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './utils.js'?
TypeScript
import { add } from "./utils.js";

console.log(add(2, 3));

./utils.js looks wrong next to utils.ts, but TypeScript maps it to the source while type-checking, and after compilation it names exactly the file Node needs. With moduleResolution set to Bundler, extensionless imports type-check fine and then crash when Node runs the output directly.

Unsupported URL scheme on Windows

Text
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in: file, data, and node are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

I ran into this one while writing a small content script for this site on Windows. The script built an absolute path and handed it straight to import().

Cause: import() takes a URL specifier, not a file system path. On macOS and Linux an absolute path like /home/me/app/post.js also happens to be a valid URL path, so the bug hides. On Windows, C:\projects\... parses as a URL whose scheme is c:, and the loader rejects it.

A raw Windows path parses as a URL with the scheme c:, while pathToFileURL gives a file: URL.
JavaScript
import path from "node:path";

const file = path.resolve("content", "post.js");
const mod = await import(file);
console.log(mod.default.title);

Fix: convert the path to a file:// URL first:

JavaScript
import path from "node:path";
import { pathToFileURL } from "node:url";

const file = path.resolve("content", "post.js");
const mod = await import(pathToFileURL(file).href);
console.log(mod.default.title);

pathToFileURL also encodes spaces and other special characters. Use it for every computed dynamic import, on every OS.

Named export not found in a CommonJS module

Text
SyntaxError: Named export 'capitalize' not found. The requested module 'legacy-strings' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'legacy-strings';
const { capitalize } = pkg;

Cause: when ESM imports a CommonJS module, Node cannot run it ahead of time to learn its exports, so it scans the source for static patterns like exports.name = .... If the exports object is built dynamically, the scan finds nothing and named imports fail. The default import, which is always module.exports, still works. Here is a package the scan cannot see through:

JavaScript
function build() {
  return {
    capitalize: (s) => s.charAt(0).toUpperCase() + s.slice(1),
    shout: (s) => s.toUpperCase() + "!",
  };
}

module.exports = build();
JavaScript
import { capitalize } from "legacy-strings";

console.log(capitalize("mathura"));

Fix: default-import, then destructure, exactly as the message suggests:

JavaScript
import legacyStrings from "legacy-strings";

const { capitalize } = legacyStrings;
console.log(capitalize("mathura"));

exports is not defined in ES module scope

Text
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'C:\projects\app\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Cause: CommonJS build output is sitting inside a "type": "module" package. The usual story is TypeScript compiling with "module": "CommonJS" into dist/index.js, which Node then loads as ESM because of the root package.json:

JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.greet = greet;
function greet(name) {
    return `Hello, ${name}`;
}
console.log(greet("Tushar"));

Fix, pick one:

  1. Emit ESM instead by setting module to NodeNext, so the output matches the package type.
  2. Rename the sources to .cts so tsc emits .cjs files, which are CommonJS whatever the type says. Relative imports between them then end in .cjs.
  3. Put a nested package.json in the output folder. Because Node uses the nearest one, this wins:
JSON
{
  "type": "commonjs"
}

Unknown file extension .ts

Text
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\projects\app\server.ts

Cause: you ran node server.ts in an ESM package on a Node version that does not handle TypeScript itself. In a CommonJS package the same mistake shows up as an ordinary SyntaxError on the first type annotation, such as Missing initializer in const declaration, because Node parses the .ts file as plain JavaScript.

Fix 1: use tsx. It transpiles on the fly, supports the full TypeScript syntax including enums, and resolves .js specifiers to .ts files:

Terminal
npx tsx server.ts

Fix 2: Node's built-in type stripping. Recent versions can run .ts files directly by erasing type annotations. It started behind --experimental-strip-types in the Node 22 line and became the default from Node 23.6, later reaching 22.x as well; check the docs for your version. On Node 24 I needed --no-experimental-strip-types to reproduce the error above. Know the limits:

  • Only erasable syntax works. Enums, namespaces with runtime code and parameter properties need --experimental-transform-types or a real compiler. Recent TypeScript versions can flag them early with erasableSyntaxOnly.
  • Type-only imports must use import type. If User is an interface, import { User } from "./types.ts" fails at runtime with does not provide an export named 'User'. The verbatimModuleSyntax setting below catches this at compile time.
  • Import specifiers must name the real file, ./utils.ts, not ./utils.js. Recent TypeScript versions accept that with allowImportingTsExtensions (alongside noEmit) or rewriteRelativeImportExtensions.
  • Node does not type-check and ignores tsconfig.json. Run tsc --noEmit in CI.
Text
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode

The tsconfig options that matter

  • module decides what the compiler emits. NodeNext emits ESM or CommonJS per file using the same rules Node uses: the type field and the .mts/.cts extensions. Recent releases also add version-pinned modes such as node20; check the docs for yours.
  • moduleResolution decides how imports are looked up. NodeNext mirrors Node: extensions required in ESM files, exports respected with the right conditions. Bundler is for code that goes through Vite, webpack or Next.js, never for code Node runs directly.
  • esModuleInterop matters when emitting CommonJS. It compiles import express from "express" into a helper that reads module.exports correctly. Without it, the default import compiles to a .default lookup that is undefined for most CommonJS packages. TypeScript turns it on by default for nodenext, but setting it explicitly costs nothing.
  • verbatimModuleSyntax emits imports and exports exactly as written. Type-only imports must say import type (otherwise error TS1484), and ESM syntax in a file that compiles to CommonJS is error TS1295 (codes from TypeScript 5.9; the exact code and wording vary between versions). What you write is what Node sees.

A config that works for a Node ESM project with "type": "module":

JSON
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

Decision table

ErrorCauseFix
Cannot use import statement outside a moduleFile loaded as CommonJS"type": "module" or .mjs
require is not defined in ES module scoperequire used in ESMimport, or createRequire(import.meta.url)
ERR_REQUIRE_ESMrequire() of an ESM-only packageawait import(), newer Node, or an ESM caller
ERR_REQUIRE_ASYNC_MODULERequired graph uses top-level awaitawait import()
__dirname is not definedCommonJS wrapper variables in ESMimport.meta.dirname or fileURLToPath
ERR_MODULE_NOT_FOUND on a relative pathMissing file extension./utils.js, also in .ts files with NodeNext
ERR_UNSUPPORTED_ESM_URL_SCHEME, protocol c:Raw Windows path passed to import()pathToFileURL(p).href
Named export 'x' not foundCommonJS exports not statically detectableDefault import, then destructure
exports is not defined in ES module scopeCommonJS output in a module packageEmit ESM, emit .cjs, or nested package.json
ERR_UNKNOWN_FILE_EXTENSION ".ts"Node not handling TypeScripttsx, or type stripping on recent Node

Checklist

  • Set "type" explicitly in every package.json you own.
  • Use .mjs or .cjs for one-off files that differ from the package type.
  • Write full relative specifiers with extensions in ESM, and no directory imports.
  • Replace __dirname with import.meta.dirname, or fileURLToPath on older Node.
  • Wrap computed paths in pathToFileURL(p).href before passing them to import().
  • When named imports from a CommonJS package fail, default-import and destructure.
  • Check node --version before applying a fix; require(esm) and type stripping depend on it.
  • For TypeScript, pair "type": "module" with NodeNext for both module and moduleResolution, plus verbatimModuleSyntax.
  • When publishing a dual package, give each build its own .d.ts or .d.cts, put types first in each exports condition block, and keep state out of the duplicated builds.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch