How to Configure the package.json exports Field
The exports field tells Node.js and modern bundlers exactly which files consumers may import and which file to load in which situation. Once it is present, anything not listed is off-limits to importers, which makes it both a packaging setting and a statement of your public API. Here is how to set it up for a typical package that ships both ES modules and CommonJS.
What you need
- Built output for each format, for example
dist/index.mjsanddist/index.cjs. - Type declarations if you publish for TypeScript users, for example
dist/index.d.ts. - A clear list of the entry points you want to support. If the answer is "just the root", that is a perfectly good answer.
Step 1: start with the root entry
Conditions are matched in the order you write them, and the first match wins. Put types first so TypeScript finds declarations, then the format-specific conditions, then a fallback.
{
"name": "example-lib",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"default": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
Keeping main and the top-level types field is harmless and helps older tooling that does not read exports. Exposing ./package.json is a small courtesy: some tools read it and fail when it is blocked.
Step 2: add subpaths deliberately
If you want users to import example-lib/utils, add an explicit "./utils" entry with its own conditions. Resist the temptation to expose a wildcard like "./*": "./dist/*" unless you genuinely want every internal file to become public API. Whatever you export, someone will depend on, and removing it later is a breaking change.
Step 3: watch the dual-package hazard
When the same package is loaded once as ESM and once as CommonJS in one application, you can end up with two copies of module-level state, such as a singleton cache or a class used in instanceof checks. If your package holds state, consider making one format a thin wrapper around the other so there is only one real implementation.
Step 4: bump the version honestly
Adding exports to a package that previously had none can break users who imported deep internal paths. Treat that first introduction as a major release, and mention it in the changelog with the list of supported entry points.
How to check it worked
- Run
npm packand install the resulting tarball into a scratch project. - From that project, try both
import x from 'example-lib'in an.mjsfile andrequire('example-lib')in a.cjsfile. - Try importing a path you did not export and confirm Node reports
ERR_PACKAGE_PATH_NOT_EXPORTED. - Optionally run community linters such as publint or Are The Types Wrong, which flag common condition-order and declaration mismatches.
If all four behave as expected, your exports map is doing its job.