The "exports" Field & ESM vs CJS
Master package entry points, conditional resolution for ES Modules and CommonJS, and subpath encapsulation using package.json exports.
What is the exports field?
The exports field in package.json defines explicit subpath mappings and condition-based entry points for a package, taking precedence over legacy main. It provides package encapsulation by blocking access to internal private files.
Why is exports critical for modern packages?
Modern Node.js applications use dual module systems (ES Modules via import and CommonJS via require()). The exports field allows a single package to serve optimized ESM builds (.mjs), CJS fallbacks (.cjs), and clean subpath shortcuts (my-pkg/utils) while preventing consumers from importing un-exported internal source files (my-pkg/src/internal.js).
How to configure conditional exports
Declare exports in package.json. Use condition keys like import, require, node, and default. Map root import . to { "import": "./dist/index.mjs", "require": "./dist/index.cjs" } and subpaths like ./utils to ./dist/utils.js.
Simulate Module Resolution
Select an import statement or resolution condition below to trace how Node.js matches package.json exports and resolves target files on disk.
Module Resolution Pipeline
Node.js export map resolution simulator
import { helper } from "my-pkg";"import" condition on root "." export
./dist/index.mjsNode.js evaluates the ES Module import statement, matches condition key "import", and resolves to the ESM bundle at ./dist/index.mjs.
"main": "./dist/index.cjs"Node.js v12.7+Module Resolver active scenario: ESM import
Remember this
- The
exportsfield takes precedence overmainin modern Node.js runtimes. - Conditional exports map
importfor ES Modules andrequirefor CommonJS. - Subpath exports provide package encapsulation, preventing consumers from importing internal private files.
- Always list
defaultas the final condition key and use fallbackmainfor legacy bundler compatibility.
Done with this concept?
Mark it complete to track your progress. No login needed.