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
.mjsis always ESM,.cjsis always CommonJS, and.jsfollows the"type"field of the nearestpackage.json(CommonJS when it is missing, though recent Node reparses files with ESM syntax as ESM and warns).- ESM has no
require,exports,__dirnameor__filename. Useimport,createRequire, andimport.meta.dirname(orfileURLToPath(import.meta.url)on older Node). - Relative ESM imports need the full file name. In TypeScript with
NodeNext, write./utils.jseven though the file on disk isutils.ts. - Never pass a raw absolute path to
import(). Convert it withpathToFileURL(p).href, or Windows fails with ac:protocol error. - Recent Node versions can
require()ES modules without top-level await and can run.tsfiles directly. Checknode --versionbefore 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:
| File | Nearest package.json | Loaded as |
|---|---|---|
.mjs or .mts | anything | ES module |
.cjs or .cts | anything | CommonJS |
.js or .ts | "type": "module" | ES module |
.js or .ts | "type": "commonjs" | CommonJS |
.js or .ts | no type field | CommonJS, 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.
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:
(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:
{
"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:
let count = 0;
export const increment = () => ++count;The CommonJS build keeps its own counter:
let count = 0;
module.exports = { increment: () => ++count };An app that reaches it both ways:
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());1 2
1The 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.
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:
const { readFile } = require("node:fs/promises");
const text = await readFile(__filename, "utf8");
console.log(text.length);SyntaxError: await is only valid in async functions and the top level bodies of modulesWrap 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
(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 moduleCause: 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.
{
"name": "my-app",
"type": "commonjs"
}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:
{
"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
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.
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:
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
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.
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:
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 throwERR_REQUIRE_ESMat all; it throwsTypeError: slugify is not a function. Writeconst { default: slugify } = require("slugify-esm").- If the package's
exportsmap has only animportcondition (norequireordefault),require()still fails, withERR_PACKAGE_PATH_NOT_EXPORTED(No "exports" main defined). Useimport()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():
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
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.
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:
import path from "node:path";
const templates = path.join(import.meta.dirname, "templates");
console.log(templates);Portable fix for older versions:
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
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\projects\app\src\utils' imported from C:\projects\app\src\index.jsCause: 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.
-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:
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'?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
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.
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:
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
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:
function build() {
return {
capitalize: (s) => s.charAt(0).toUpperCase() + s.slice(1),
shout: (s) => s.toUpperCase() + "!",
};
}
module.exports = build();import { capitalize } from "legacy-strings";
console.log(capitalize("mathura"));Fix: default-import, then destructure, exactly as the message suggests:
import legacyStrings from "legacy-strings";
const { capitalize } = legacyStrings;
console.log(capitalize("mathura"));exports is not defined in ES module scope
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:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.greet = greet;
function greet(name) {
return `Hello, ${name}`;
}
console.log(greet("Tushar"));Fix, pick one:
- Emit ESM instead by setting
moduletoNodeNext, so the output matches the package type. - Rename the sources to
.ctssotscemits.cjsfiles, which are CommonJS whatever thetypesays. Relative imports between them then end in.cjs. - Put a nested
package.jsonin the output folder. Because Node uses the nearest one, this wins:
{
"type": "commonjs"
}Unknown file extension .ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\projects\app\server.tsCause: 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:
npx tsx server.tsFix 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-typesor a real compiler. Recent TypeScript versions can flag them early witherasableSyntaxOnly. - Type-only imports must use
import type. IfUseris an interface,import { User } from "./types.ts"fails at runtime withdoes not provide an export named 'User'. TheverbatimModuleSyntaxsetting below catches this at compile time. - Import specifiers must name the real file,
./utils.ts, not./utils.js. Recent TypeScript versions accept that withallowImportingTsExtensions(alongsidenoEmit) orrewriteRelativeImportExtensions. - Node does not type-check and ignores
tsconfig.json. Runtsc --noEmitin CI.
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only modeThe tsconfig options that matter
- module decides what the compiler emits.
NodeNextemits ESM or CommonJS per file using the same rules Node uses: thetypefield and the.mts/.ctsextensions. Recent releases also add version-pinned modes such asnode20; check the docs for yours. - moduleResolution decides how imports are looked up.
NodeNextmirrors Node: extensions required in ESM files,exportsrespected with the right conditions.Bundleris 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 readsmodule.exportscorrectly. Without it, the default import compiles to a.defaultlookup that isundefinedfor most CommonJS packages. TypeScript turns it on by default fornodenext, but setting it explicitly costs nothing. - verbatimModuleSyntax emits imports and exports exactly as written. Type-only imports must say
import type(otherwise errorTS1484), and ESM syntax in a file that compiles to CommonJS is errorTS1295(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":
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src"]
}Decision table
| Error | Cause | Fix |
|---|---|---|
Cannot use import statement outside a module | File loaded as CommonJS | "type": "module" or .mjs |
require is not defined in ES module scope | require used in ESM | import, or createRequire(import.meta.url) |
ERR_REQUIRE_ESM | require() of an ESM-only package | await import(), newer Node, or an ESM caller |
ERR_REQUIRE_ASYNC_MODULE | Required graph uses top-level await | await import() |
__dirname is not defined | CommonJS wrapper variables in ESM | import.meta.dirname or fileURLToPath |
ERR_MODULE_NOT_FOUND on a relative path | Missing 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 found | CommonJS exports not statically detectable | Default import, then destructure |
exports is not defined in ES module scope | CommonJS output in a module package | Emit ESM, emit .cjs, or nested package.json |
ERR_UNKNOWN_FILE_EXTENSION ".ts" | Node not handling TypeScript | tsx, or type stripping on recent Node |
Checklist
- Set
"type"explicitly in everypackage.jsonyou own. - Use
.mjsor.cjsfor one-off files that differ from the package type. - Write full relative specifiers with extensions in ESM, and no directory imports.
- Replace
__dirnamewithimport.meta.dirname, orfileURLToPathon older Node. - Wrap computed paths in
pathToFileURL(p).hrefbefore passing them toimport(). - When named imports from a CommonJS package fail, default-import and destructure.
- Check
node --versionbefore applying a fix;require(esm)and type stripping depend on it. - For TypeScript, pair
"type": "module"withNodeNextfor bothmoduleandmoduleResolution, plusverbatimModuleSyntax. - When publishing a dual package, give each build its own
.d.tsor.d.cts, puttypesfirst in eachexportscondition block, and keep state out of the duplicated builds.