What you'll learn: By the end of this lesson you will be able to say which module format a file has, read a
package.jsonexportsmap and predict the file a given import resolves to (including conditions, subpath patterns and blocked paths), explain how a package that ships both ES module and CommonJS builds can be loaded twice with separate state, and write a browser-target query that you can reason about, including what it costs in rewritten syntax.
Think of an office building with a lobby directory. A visitor can only reach the rooms listed on the directory, even though many more rooms exist behind the doors. The directory can send a courier to one entrance and a client to another. If the building has two lobbies with two reception desks, a visitor who signs in at one desk is unknown at the other. And the building has a dress code, which decides what everyone must wear to get in. Package exports is the directory, the two entrances are the two module formats, and the browser target is the dress code.
This lesson builds on the build pipeline in the previous lesson, Bundlers and Build Tooling, whose first stage, resolve, is the subject here. What the module language itself guarantees (live bindings, cycles, evaluation order) is in JavaScript Modules and TypeScript at Scale, and the same lesson's lab, esm-module-semantics, runs real Node modules; this lesson's lab models only the lookup. Splitting output is in Code Splitting, Lazy Loading and Tree Shaking.
The core idea
- A file's format comes from its extension and its nearest
package.json..mjsis always an ES module and.cjsalways CommonJS; for.js, the"type"field decides. exportsis the public map of a package: a name plus a subpath goes in, a file comes out, and a path not on the map cannot be imported.- Conditions choose among files by who is asking (Node's
importorrequire, a browser, a type checker). Keys are tried in order and the first match wins. - Shipping two formats can give an app two copies of the same module, each with its own state.
- Browser targets say which syntax must be rewritten. A wide target list costs extra transforms for browsers that may not matter.
Versions at the time of writing: the Node.js pages read were for v26.14.0; the lab ran on Node 26.13.1. Option names come from the Node, TypeScript, Vite and Browserslist pages listed at the end.
Which format is this file?
Node's documentation says: "A package.json "type" value of "module" tells Node.js to interpret .js files within that package as using ES module syntax." If the field is missing or "commonjs", .js files are CommonJS. "Regardless of the value of the "type" field, .mjs files are always treated as ES modules and .cjs files are always treated as CommonJS."
Two more rules matter when formats meet. In Node's ES module loader, "a file extension must be provided when using the import keyword to resolve relative or absolute specifiers", so ./cart fails where ./cart.js works. And require of an ES module "currently only supports loading synchronous ES modules (that is, ES modules that do not use top-level await)". A bundler resolves imports its own way and usually does not insist on extensions, which is one reason code can work in the bundle and fail in Node.
Exports: the public map
Without exports, a package's main is its entry and any file path inside it can be imported. With exports, Node's documentation says "all subpaths of the package are encapsulated and no longer available to importers", and "the "exports" field, if it exists, takes precedence over the "main" field when importing the package by name". It recommends exports "for new packages targeting the currently supported versions of Node.js". Importing a path that is not exported fails with ERR_PACKAGE_PATH_NOT_EXPORTED, which Node describes as: "Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution".
Three forms cover most packages:
- Subpaths.
"./format": "./dist/format.mjs"publishespkg/format. - Patterns.
"./locales/*": "./dist/locales/*.mjs";*is "a string replacement syntax only" and may contain/. To hide a folder, map it tonull: Node's own example excludes./features/private-internal/*while exposing./features/*.js. - Conditions. A key such as
import,require,browserortypesselects a target by who asks. "Within the"exports"object, key order is significant. During condition matching, earlier entries have higher priority."default"should always come last".importandrequireare "always mutually exclusive". The communitytypescondition "should always be included first", and conditions can nest.
Figure 1. How one request is resolved
How to read this: the first fork is the one that makes adding an exports field a breaking change for anyone who imported internal files.
Illustration 1, the minimal example: one package, four requesters
The lab, package-exports-resolver, is a model of the lookup, not Node: it reads in-memory package.json objects. The condition set each requester matches is chosen for the lab (the browser bundler set is illustrative; each real tool documents its own). The package @shopstream/money maps . to nested import and require conditions, each with a types entry first and a default after.
Expected output, captured from a real run (scenario 1):
=== 1. One package, four requesters (conditions: node+import, node+require, browser+import+production, types+import)
@shopstream/money . as "node import" -> ./dist/index.mjs [exports["."] > import > default]
@shopstream/money . as "node require" -> ./dist/index.cjs [exports["."] > require > default]
@shopstream/money . as "browser bundler" -> ./dist/index.mjs [exports["."] > import > default]
@shopstream/money . as "typescript bundler resolution" -> ./dist/index.d.mts [exports["."] > import > types]
The same import name gives a JavaScript file to three requesters and a declaration file to the type checker. TypeScript follows the same rules: it follows Node's exports handling under node16, nodenext and bundler resolution, always matches the types and default conditions, and when exports is read it ignores main and types fields. The docs add that the presence of exports "prevents resolving any subpaths that cannot be matched". Extra conditions can be added with customConditions. Vite's resolve.conditions defaults to ['module', 'browser', 'development|production'], so a bundler's set is its own.
Figure 2. One package, several requesters, several files
How to read this: every requester goes through the map. The Node import and the bundler both reach the ES module file in the lab's condition sets, and only the type checker is sent to declarations.
Encapsulation and order
Expected output, captured from a real run (scenarios 2 and 3):
@shopstream/money ./format as "node import" -> ./dist/format.mjs [exports["./format"]]
@shopstream/money ./dist/format.mjs as "node import" -> ERR_PACKAGE_PATH_NOT_EXPORTED: @shopstream/money does not export "./dist/format.mjs"
@shopstream/money ./locales/en as "node import" -> ./dist/locales/en.mjs [exports["./locales/*"]]
@shopstream/money ./locales/internal/tax as "node import" -> ERR_PACKAGE_PATH_NOT_EXPORTED: @shopstream/money does not export "./locales/internal/tax"
legacy-fmt . as "node import" -> ./lib/index.js [main]
legacy-fmt ./lib/private.js as "node import" -> ./lib/private.js [no exports field: any file path in the package works]
The real file dist/format.mjs exists but cannot be imported by its path; the pattern exposes en; the null entry hides the internal folder; and the old package with no exports leaves everything open. One more case from the lab: a package that lists default before import always resolves to the default target, because the first matching key wins and default matches everything. That is the single most common mistake in a hand-written map.
Two formats, two copies
If import maps to one file and require to another, an app that imports the package and a library that requires it each get a different file. Node's page only says that using the two conditions "can lead to some hazards"; the model shows the one that matters for front ends. It keeps one instance (a counter) per implementation file, loads the package once through import and once through require, and adds 2 to the app's counter.
Figure 3. The two copies
How to read this: two files mean two module instances, so a store or a registry in the package is not shared between the callers.
Illustration 2, the realistic example: a cart store that is two stores
@shopstream/cart-store is an illustrative shared package used by the storefront (ES modules) and by a partner widget library (CommonJS). Expected output, captured from a real run (scenario 4):
=== 4. Two formats, two instances (the dual package problem)
--- separate implementations
app (import) uses instance 1 from ./dist/index.mjs
library (require) uses instance 2 from ./dist/index.cjs
app added 2 to its counter; library sees 0
--- ES file wraps the one implementation
app (import) uses instance 1 from ./dist/index.cjs
library (require) uses instance 1 from ./dist/index.cjs
app added 2 to its counter; library sees 2
The fix in the second half is one implementation file with a thin ES wrapper that re-exports it. Other fixes are to ship one format only, or to keep no state in the package. Which is safe depends on your consumers' Node versions, so verify against the Node page for the versions you support.
Browser targets
A target is a list of browsers and versions the output must run on. Browserslist is a shared way to write it. Queries combine: "An or combiner can use the keyword or as well as ,", and is "an intersection of all the previous queries", "you can add not to any query", and "you can not start with a not combiner". last 2 versions means "the last 2 versions for each browser", and defaults is > 0.5%, last 2 versions, Firefox ESR, not dead, where dead means "browsers without official support or updates for 24 months". The query lives in a browserslist key in package.json or in .browserslistrc; it can differ per environment, read from BROWSERSLIST_ENV or NODE_ENV. Its data comes from caniuse-lite, and update-browserslist-db refreshes it. The README lists Autoprefixer and Babel among the tools that use it. Some tools take their own setting instead: Vite's build.target defaults to baseline-widely-available and does not follow tsconfig.json's target.
Figure 4. From a query to rewritten syntax
How to read this: the query is only text until it meets data. The same query gives different targets after the data is updated.
Illustration 3, the edge case: when a query goes wrong
The lab's queries run over invented browsers (alpha, beta, gamma, with gamma marked dead) and invented support data for three syntax features. Nothing here is a statement about a real browser, and the real tool supports many more query forms.
Expected output, captured from a real run (scenario 5):
=== 5. Browser targets: invented browsers (alpha, beta, gamma) and invented support data
query: last 2 versions
targets: alpha: 106, 107 | beta: 17, 18 | gamma: 11, 12
transforms needed: optional-chaining, private-class-fields, top-level-await
query: last 2 versions, not dead
targets: alpha: 106, 107 | beta: 17, 18
transforms needed: top-level-await
query: alpha >= 102, beta >= 15, not dead
targets: alpha: 102, 103, 104, 105, 106, 107 | beta: 15, 16, 17, 18
transforms needed: private-class-fields, top-level-await
query: alpha >= 107 and beta >= 18
targets: none
transforms needed: none
query: alpha >= 107, beta >= 18
targets: alpha: 107 | beta: 18
transforms needed: none
query: not dead
error: a query cannot start with "not"
Read it as three lessons. One dead browser in the list forces every transform (second line). A comma and an and are not the same: joining two different browsers with and leaves nothing. And a query that starts with not is rejected. Two cautions about the "needs no transforms" lines: an empty target list means the build assumes nothing and the output is untested for everyone, and the real data and feature tables change as browsers ship.
Trade-offs
| Choice | Gains | Costs |
|---|---|---|
exports map |
Private files stay private; conditions pick the right file | Adding it breaks deep imports; every public path must be listed |
No exports |
Anything can be imported | Consumers depend on your internals |
| Dual ES and CommonJS builds | Works for old and new consumers | Two instances unless one file implements both |
| ESM only | One format, no dual copy | Consumers must be able to load ES modules |
| Wide browser target | Reaches older browsers | More rewritten syntax and polyfills |
| Narrow target | Smaller, closer-to-source output | Breaks users outside it |
Build it: the exports resolver
Goal. Run the lookup and the query rules on small fixtures and read the output next to the rules above.
cd examples/frontend/labs/package-exports-resolver
pnpm test # 25 tests
pnpm typecheck
node src/demo.ts # prints the five scenarios shown above
This is a model, not Node or Browserslist. It follows the rules stated on the pages listed at the end, over in-memory data. It takes the longest prefix when two patterns match, which the Node page's null example relies on but does not state as a rule, and it implements only a handful of query forms over invented browsers. It does not show how a real loader caches modules or how any real browser behaves.
Break it. In a scratch copy of src/fixtures.ts, move default to the end of the wrongOrder package; the "first matching key wins" test fails because import is now reached first. Restore it.
In practice: a shared cart store that shows an empty cart
This is a realistic scenario, not a case history.
The situation
ShopStream's storefront and a partner's widget library both use @shopstream/cart-store. Shoppers add items on the storefront, but the widget's cart badge shows zero.
Starting architecture
Figure 5. Two consumers, two files
How to read this: the red arrow is the second copy. State written through one file is invisible to the other.
Options considered
| Option | Result | Risk |
|---|---|---|
| Make the ES file wrap the CommonJS implementation | One instance | The ES file now depends on CommonJS interop |
| Ship only ES modules | One format | The partner must be able to load ES modules |
| Move state out of the package into the app | No shared singleton | Callers must pass the store in |
The decision
Keep both entries, make the ES file a thin wrapper, and add a test that loads the package through both conditions and asserts the same instance.
Rollout and verification
Release as a minor version, add the two-condition test to the package's CI, and ask the partner to confirm the badge after upgrading.
The 2 a.m. failure
In the same release a maintainer tidies the package by adding a stricter exports map without the old lib/ paths. A different partner's nightly build, which imports cart-store/lib/private.js, fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Because exports encapsulates every path not listed, adding it is a breaking change for deep importers. The rollback is to publish the previous version again; the lasting fix is to list supported subpaths first, announce removals, and release the encapsulation as a major version.
Architect's notes
- Treat adding or tightening
exportsas a breaking change. - Put
typesfirst anddefaultlast in every conditions object. - Prefer one implementation file over two copies of state.
- Choose targets from your own traffic, and write the query where tools can read it.
- Test the lookup through every condition your consumers use.
Common mistakes
- Putting
defaultbeforeimportorrequire. - Assuming a bundler's resolution is the same as Node's.
- Importing internal files that
exportshides, then upgrading. - Joining two browsers with
andand getting an empty target. - Leaving dead browsers in the list without deciding to.
- Letting
mainandtypesfields drift whileexportsis what is read.
Key takeaways
- Extension and
typedecide a file's format. exportsis the public map; unlisted paths are not importable.- Condition order is significant;
typesfirst,defaultlast. - Two formats can mean two instances.
- A target is a query plus data, and data changes.
- A wider target costs rewritten syntax.
Practice exercises
Exercise 1, easy (20 minutes). Open a package in your node_modules that has exports, and write down which file each of import, require and types reaches.
Exercise 2, intermediate (45 minutes). Extend the lab with a ./utils/* pattern and a more specific exact key, and test which one wins.
Exercise 3, intermediate (60 minutes). Write your app's browser query, list the browsers it resolves to in your tool, and note which syntax your build rewrites because of the oldest one.
Related reading
- JavaScript Modules and TypeScript at Scale: evaluation, live bindings and its
esm-module-semanticslab. - Code Splitting, Lazy Loading and Tree Shaking: what the bundler does after resolution.
- Module Boundaries and Public APIs: the same idea inside one app.
- Monorepos and Shared Libraries: publishing shared packages.
- Dependency and Supply-Chain Security: what you pull in.
- Build performance and caching, runtime configuration and CI/CD for front ends are later lessons in this module.
Official documentation
- Modules: Packages (Node.js):
exports, patterns, conditions,type. - ECMAScript modules (Node.js): file extensions and
requireof ES modules. - Errors (Node.js):
ERR_PACKAGE_PATH_NOT_EXPORTED. - Modules reference (TypeScript):
exports,types,customConditions. - Browserslist README: queries, config, environments.
- Shared options (Vite):
resolve.conditions; also Build options forbuild.target.