Thuta Learning
Node.js
BasicWeb DevelopmentBeginner

ES Modules, package.json & Exports

Node.jsLesson 630 min

What you'll walk away with

  • Decide whether a file is ESM or CommonJS from its extension and package.json's "type"
  • Write relative imports with the full .js extension and use top-level await
  • Locate files next to a module with import.meta.url or import.meta.dirname instead of __dirname
  • Define a package's public entry points with an "exports" map and block deep imports

Explain it simply

Explain it simply

ES modules (ESM) are the standard module system of the JavaScript language itself, the same import/export you use in browsers. CommonJS is the system Node invented for itself before ESM existed. Node runs both, so for every file it needs to know which set of rules applies.

Think of a package as a shop. Its "exports" map lists the front doors: customers may enter only through the doors you open, never straight into the storeroom of internal files at the back.

Problem → Why → Solution

The problem: CommonJS habits break in ESM

On the day a project switches to "type": "module", the app often stops with three kinds of error at once. Imports without an extension no longer resolve, __dirname is gone, and a direct import of a library's internal file breaks after the library updates. The file below contains all three.

src/index.js
// package.json now says: "type": "module"
import { slugify } from "./utils";              // ERR_MODULE_NOT_FOUND
import { parse } from "some-lib/dist/parser.js"; // ERR_PACKAGE_PATH_NOT_EXPORTED

const configPath = __dirname + "/config.json";
// ReferenceError: __dirname is not defined in ES module scope

Why does this happen?

ESM resolves files like URLs, the way browsers do, so it never guesses extensions. Without the CommonJS wrapper there is no __dirname, require or module either. And when a package declares an "exports" map, Node blocks every path that the map does not list.

Core concept: declare the module type, control the entry points

Node's rule for how to read a file is simple. .mjs is always ESM and .cjs is always CommonJS. A .js file follows the nearest package.json: "type": "module" means ESM, while "commonjs" or no field means CommonJS. Recent Node versions re-read an untyped .js file as ESM when they find import/export syntax in it, but they print a warning and pay a performance cost, so always declare the type.

In ESM, import and export are static, so Node finds and loads every dependency before any code runs. Relative imports need the full extension, as in "./utils.js". ESM files run in strict mode automatically and support top-level await: you can write const data = await readFile(...) directly, without wrapping it in a function.

Because __dirname and __filename no longer exist, you use import.meta instead. import.meta.url is the module's file:// URL, and new URL("./config.json", import.meta.url) points at a file next to the module; since Node 20.11 there are also import.meta.dirname and import.meta.filename. ESM can import CommonJS modules: the default import always gives you module.exports, while named imports work only when Node can detect the names statically, as with exports.name = ... or module.exports = { name }.

From the package's side, the "exports" field in package.json defines the public API. "." is the file behind import "greet-kit", and subpaths such as "./format" serve import "greet-kit/format". Importing any path missing from the map fails with ERR_PACKAGE_PATH_NOT_EXPORTED, which lets the package author move internal files around without breaking anyone.

FileHow Node reads it
*.mjsESM, wherever it lives
*.cjsCommonJS, wherever it lives
*.js + "type": "module"ESM
*.js + no type / "commonjs"CommonJS (recent Node re-reads it as ESM, with a warning, if it finds ESM syntax)
Mental model: how one import resolves
  1. Extension and type pick the system
  2. Relative paths resolve like URLs
  3. Bare names go through exports
  4. Unlisted package paths are blocked

ESM guesses nothing: you spell out extensions and entry points yourself.

General pattern: an ES module and an exports map

javascript
// package.json: { "type": "module",
//   "exports": { ".": "./src/index.js", "./sub": "./src/sub.js" } }

import { named } from "./relative-file.js"; // full extension
import defaultThing from "package-name";
import { helper } from "package-name/sub";

export function publicName() { /* ... */ }
const nearby = new URL("./data-file.json", import.meta.url);

Write the full extension on relative imports and import packages only through the names their exports map declares. The export keyword marks what is public, and new URL(..., import.meta.url) points at a file next to the module.

Example: a tiny ESM package with an exports map

This script builds a node_modules/greet-kit package inside a temporary folder, just as if npm had installed it. Then app.mjs imports the package by name, uses a subpath export and tries to import an internal file that the exports map leaves out. Watch which imports succeed and which one is blocked.

esm-demo.mjs
// esm-demo.mjs - a tiny ESM package with an "exports" map
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";

const root = await mkdtemp(join(tmpdir(), "esm-demo-"));
const pkgDir = join(root, "node_modules", "greet-kit");
await mkdir(join(pkgDir, "src"), { recursive: true });

// The package: ES modules, two public entry points, one private file.
await writeFile(join(pkgDir, "package.json"), JSON.stringify({
  name: "greet-kit",
  type: "module",
  exports: { ".": "./src/index.js", "./format": "./src/format.js" },
}));
await writeFile(join(pkgDir, "src", "format.js"),
  "export const shout = (text) => text.toUpperCase() + '!';\n");
await writeFile(join(pkgDir, "src", "index.js"),
  "import { shout } from './format.js';\n" +
  "export const greet = (name) => shout('hello ' + name);\n");
await writeFile(join(pkgDir, "src", "internal.js"), "export const secret = 42;\n");

// A consumer that imports the package by name, like any npm dependency.
await writeFile(join(root, "app.mjs"), [
  "import { greet } from 'greet-kit';",
  "import { shout } from 'greet-kit/format';",
  "console.log(greet('node'));",
  "console.log(shout('subpath export'));",
  "try { await import('greet-kit/src/internal.js'); }",
  "catch (err) { console.log('Deep import blocked:', err.code); }",
].join("\n"));

await import(pathToFileURL(join(root, "app.mjs")).href);
await rm(root, { recursive: true, force: true });

Code breakdown

  1. Line 7const root = await mkdtemp(join(tmpdir(), "esm-demo-"));

    Using await directly, outside any function, is top-level await, which only ESM allows. mkdtemp appends random characters to the prefix and creates a fresh folder.

  2. Lines 12-16exports: { ".": "./src/index.js", "./format": "./src/format.js" },

    "type": "module" makes the package's .js files ESM. The exports map opens exactly two public doors and leaves internal.js off the list.

  3. Line 20import { shout } from './format.js';

    Inside the package, one file imports another with a relative path and the full .js extension. The exports map does not restrict relative imports within the package.

  4. Lines 26-27import { shout } from 'greet-kit/format';

    The consumer imports the package by name. Node finds node_modules/greet-kit, reads its exports map and translates "./format" into ./src/format.js.

  5. Lines 30-31try { await import('greet-kit/src/internal.js'); }

    The file really exists on disk, but it is not in the exports map, so Node refuses with ERR_PACKAGE_PATH_NOT_EXPORTED. Dynamic import() returns a Promise, so try/catch can catch the error.

  6. Line 34await import(pathToFileURL(join(root, "app.mjs")).href);

    ESM locates modules by URL, so the disk path is converted to a file:// URL with pathToFileURL() before it is passed to import(). On Windows, with paths starting C:\, this step is essential.

You should see
HELLO NODE!
SUBPATH EXPORT!
Deep import blocked: ERR_PACKAGE_PATH_NOT_EXPORTED

import.meta: asking "where am I?" in ESM

Run this snippet as a .mjs file. It confirms that __dirname is missing, that import.meta.url is a file: URL, that import.meta.filename equals that URL converted to a path, and that new URL(..., import.meta.url) points next to the module. Full paths differ per machine, so it prints only true/false checks.

The last check matters most in practice. new URL("./config.json", import.meta.url) resolves against the module's own location, so the file is found no matter which folder the terminal was in when you ran node. A plain "./config.json" handed to readFile would instead resolve against process.cwd() and break as soon as someone starts the app from a different folder, for example through an npm script in a parent directory or a service manager on a server.

paths.mjs
// paths.mjs - where am I? (ES module edition)
import { fileURLToPath } from "node:url";

console.log("typeof __dirname:", typeof __dirname);
console.log("import.meta.url scheme:", new URL(import.meta.url).protocol);
console.log("filename matches:", import.meta.filename === fileURLToPath(import.meta.url));
const configUrl = new URL("./config.json", import.meta.url);
console.log("config URL ends with:", configUrl.pathname.endsWith("/config.json"));

In real projects

How this plays out in real projects

Most new projects start with "type": "module", and tools such as Vite and Vitest, along with newer frameworks, default to ESM. Some packages have become ESM-only, so CommonJS projects load them with await import("pkg"); Node 22.12 and later can also require() an ES module that has no top-level await (check the docs for your exact version).

Library authors treat the exports map as the contract of their public API: any file not in the map can be moved or renamed without counting as a breaking change. You will also see "import" and "require" conditions that hand ESM and CommonJS consumers different files, known as a dual package. Applications use the related "imports" field to declare private aliases such as "#db" and avoid long ../../../ chains.

Common mistakes

Common mistakes

1. Dropping the extension from a relative import

import { slugify } from "./utils" fails in ESM with ERR_MODULE_NOT_FOUND, and Node suggests "Did you mean to import "./utils.js"?". When migrating from CommonJS, add .js to every relative import, and write folders out in full as "./lib/index.js".

2. Using __dirname or require inside ESM

In an ESM file, __dirname throws "ReferenceError: __dirname is not defined in ES module scope". Use import.meta.dirname or new URL("./file", import.meta.url). If you truly must require a CommonJS-only package, use createRequire(import.meta.url) from node:module.

3. Deep-importing a package's internal file

A path such as "some-lib/dist/parser.js" may have worked before the package added an exports map, then suddenly fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Import only the entry points the package documents.

Best practices

Best practices

  • Add "type": "module" to every new project on day one; switching later is harder.
  • Import built-ins with the node: prefix and your own files with the full .js extension.
  • Ship an exports map from a package's first release: the smaller the public API, the easier it is to maintain.
  • Resolve files that sit next to a module through import.meta, never through process.cwd().

Mini challenge

Mini challenge: read a config next to a module and talk to CommonJS

In an ES module, write loadJson(fileName, moduleUrl), which resolves the file against a module URL and parses its JSON. Then load a CommonJS file both with createRequire() and with import(). Create every file inside a temporary folder.

  • Resolve the file with new URL(fileName, moduleUrl) and read it with readFile from node:fs/promises
  • Write config.json and legacy.cjs into a temporary folder
  • Require legacy.cjs through createRequire(moduleUrl)
  • Show that loading it with import() gives module.exports as the default export
  • Delete the temporary folder in a finally block
load-config.mjs
// load-config.mjs - files next to a module, plus CommonJS interop
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";

async function loadJson(fileName, moduleUrl) {
  // TODO: resolve fileName next to moduleUrl, read it as UTF-8, parse JSON
}

const dir = await mkdtemp(join(tmpdir(), "esm-config-"));
try {
  // TODO: moduleUrl = file URL of an imaginary app.mjs inside dir
  // TODO: write config.json ({ name, port }) and legacy.cjs (exports double)
  // TODO: print the config, require legacy.cjs, then import() it
} finally {
  // TODO: remove dir
}

Expected: The output should be: Config: task-api on port 3000 require('./legacy.cjs').double(21) = 42 import() of CommonJS, default export: [ 'double' ]

Show hint

pathToFileURL(join(dir, "app.mjs")) gives the same kind of URL that import.meta.url would be for a module in dir; the file does not need to exist. createRequire() also accepts a URL or an absolute path. In the result of import(), module.exports sits under .default.

Show solution
load-config.mjs
// load-config.mjs - files next to a module, plus CommonJS interop
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";

async function loadJson(fileName, moduleUrl) {
  const fileUrl = new URL(fileName, moduleUrl); // resolved next to the module
  return JSON.parse(await readFile(fileUrl, "utf8"));
}

const dir = await mkdtemp(join(tmpdir(), "esm-config-"));
try {
  // Stands in for import.meta.url of a module saved inside dir.
  const moduleUrl = pathToFileURL(join(dir, "app.mjs"));
  const config = { name: "task-api", port: 3000 };
  await writeFile(join(dir, "config.json"), JSON.stringify(config));
  await writeFile(join(dir, "legacy.cjs"), "exports.double = (n) => n * 2;\n");

  const loaded = await loadJson("./config.json", moduleUrl);
  console.log(`Config: ${loaded.name} on port ${loaded.port}`);

  const require = createRequire(moduleUrl);
  const { double } = require("./legacy.cjs");
  console.log("require('./legacy.cjs').double(21) =", double(21));

  const legacy = await import(new URL("./legacy.cjs", moduleUrl).href);
  console.log("import() of CommonJS, default export:", Object.keys(legacy.default));
} finally {
  await rm(dir, { recursive: true, force: true });
}

Quick quiz 1 / 3

package.json has no "type" field. Which file is always treated as ESM?

Quick quiz 2 / 3

Inside an ES module, what gives you the folder that contains the file?

Quick quiz 3 / 3

A package's exports is only { ".": "./src/index.js" }. What does import "greet-kit/src/format.js" do?

What to remember

  • .mjs is ESM, .cjs is CommonJS, and .js follows package.json's "type"; always declare it.
  • In ESM, write full extensions on relative imports; top-level await is available.
  • Replace __dirname with import.meta.dirname or new URL("./file", import.meta.url).
  • The "exports" map is a package's public API; unlisted paths fail with ERR_PACKAGE_PATH_NOT_EXPORTED.

Packages — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

ES Modules, package.json & Exports | Thuta Learning