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

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

  1. Run npm pack and install the resulting tarball into a scratch project.
  2. From that project, try both import x from 'example-lib' in an .mjs file and require('example-lib') in a .cjs file.
  3. Try importing a path you did not export and confirm Node reports ERR_PACKAGE_PATH_NOT_EXPORTED.
  4. 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.

Related pages