Skip to content

    Frontend System Design

    Module Formats, Package Exports and Browser Targets

    How package.json exports and conditions turn an import into a file, why two module formats can mean two copies, and how browser targets drive transforms.

    By Published 11 min read

    • frontend-system-design
    • package-exports
    • browserslist
    • module-formats
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Bundlers and Build Tooling

    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.json exports map 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

    1. A file's format comes from its extension and its nearest package.json. .mjs is always an ES module and .cjs always CommonJS; for .js, the "type" field decides.
    2. exports is 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.
    3. Conditions choose among files by who is asking (Node's import or require, a browser, a type checker). Keys are tried in order and the first match wins.
    4. Shipping two formats can give an app two copies of the same module, each with its own state.
    5. 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" publishes pkg/format.
    • Patterns. "./locales/*": "./dist/locales/*.mjs"; * is "a string replacement syntax only" and may contain /. To hide a folder, map it to null: Node's own example excludes ./features/private-internal/* while exposing ./features/*.js.
    • Conditions. A key such as import, require, browser or types selects 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". import and require are "always mutually exclusive". The community types condition "should always be included first", and conditions can nest.

    Figure 1. How one request is resolved

    flowchart TD accTitle: How a package request is resolved accDescr: A decision tree. If the package has no exports field, the main field is the entry and any file path works. If it has exports, the request is matched to an exact key or the best pattern; if none matches, the path is not exported. A matched target that is a conditions object is searched in key order, the first matching condition wins, and default always matches. A{exports field present?} -->|no| B[main is the entry, any file path works] A -->|yes| C{subpath matches an exact key or a pattern?} C -->|no| D[not exported: ERR_PACKAGE_PATH_NOT_EXPORTED] C -->|yes| E{target is a conditions object?} E -->|no| F[the target file] E -->|yes| G[first key in order that matches, default always matches]

    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

    Node import, Node require, a browser bundler and the type checker each reach a different file of the same packageNode import to exports map (asks); Node require to exports map (asks); Bundler to exports map (asks); Type checker to exports map (asks); exports map to index.mjs (import); exports map to index.cjs (require); exports map to index.d.mts (types)Node import: node, importNode importnode, importNode require: node, requireNode requirenode, requireBundler: browser, importBundlerbrowser, importType checker: types, importType checkertypes, importexports map: money packageexports mapmoney packageindex.mjs: ES moduleindex.mjsES moduleindex.cjs: CommonJSindex.cjsCommonJSindex.d.mts: types onlyindex.d.mtstypes onlyasksasksasksasksimportrequiretypes

    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

    sequenceDiagram accTitle: A dual package loaded as two separate copies accDescr: The app imports the package and gets the ES module file with its own counter. A library requires the same package and gets the CommonJS file with a separate counter. The app increments its counter to 2. The library still reads 0. participant A as App (import) participant M as index.mjs, counter 1 participant L as Library (require) participant C as index.cjs, counter 2 A->>M: add 2 L->>C: read C-->>L: 0

    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

    A query is resolved against browser data into targets, which a feature table turns into the transforms the build must applyQuery to Targets (resolve); Browser data to Targets (lookup); Targets to Transforms (compare); Feature table to Transforms (needs)Query: last 2 versionsQuerylast 2 versionsBrowser data: versions, dead flagsBrowser dataversions, deadflagsTargets: browser + versionTargetsbrowser + versionFeature table: first supported versionFeature tablefirst supportedversionTransforms: syntax to rewriteTransformssyntax to rewriteresolvelookupcompareneeds

    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

    The storefront imports the ES module file and the widget requires the CommonJS file of the same packageStorefront to cart-store (import); Partner widget to cart-store (require); cart-store to index.mjs (import); cart-store to index.cjs (require)Storefront: ES modulesStorefrontES modulesPartner widget: CommonJSPartner widgetCommonJScart-store: exports mapcart-storeexports mapindex.mjs: own stateindex.mjsown stateindex.cjs: own stateindex.cjsown stateimportrequireimportrequire

    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 exports as a breaking change.
    • Put types first and default last 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 default before import or require.
    • Assuming a bundler's resolution is the same as Node's.
    • Importing internal files that exports hides, then upgrading.
    • Joining two browsers with and and getting an empty target.
    • Leaving dead browsers in the list without deciding to.
    • Letting main and types fields drift while exports is what is read.

    Key takeaways

    • Extension and type decide a file's format.
    • exports is the public map; unlisted paths are not importable.
    • Condition order is significant; types first, default last.
    • 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.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments