Browse topics

Package exports and conditional entry points

Version
24
Since
12.7.0
Review
Draft

Summary#

Use exports in package.json to define the entry points that callers can load by package name. A conditional entry point can choose a different file for import and require().

Syntax#

json
{
  "exports": {
    ".": {
      "import": "./label.mjs",
      "require": "./label.cjs",
      "default": "./label.mjs"
    },
    "./prefix": "./prefix.cjs"
  }
}

The "." key handles the bare package name. A key like "./prefix" handles a request for package-name/prefix. File targets start with ./. Node checks conditions in the order given and uses the first match.

Example#

Create a local package fixture and load it from ESM and CommonJS. The same prefix.cjs file is reachable through its public subpath.

sh
(
  set -eu
  temp_root=$(CDPATH= cd -- "${TMPDIR:-/tmp}" && pwd -P)
  work_dir=$(mktemp -d "$temp_root/dlr-nodejs-exports-XXXXXXXX")
  trap 'rm -rf -- "$work_dir"' 0
  trap 'exit 1' HUP INT TERM
  cd "$work_dir"
  unset NODE_OPTIONS NODE_COMPILE_CACHE NODE_V8_COVERAGE

  mkdir -p node_modules/shelf-labels
  cat > node_modules/shelf-labels/package.json <<'JSON'
{
  "name": "shelf-labels",
  "exports": {
    ".": {
      "import": "./label.mjs",
      "require": "./label.cjs",
      "default": "./label.mjs"
    },
    "./prefix": "./prefix.cjs"
  }
}
JSON
  printf '%s\n' 'export default "label from ESM";' > node_modules/shelf-labels/label.mjs
  printf '%s\n' 'module.exports = "label from CommonJS";' > node_modules/shelf-labels/label.cjs
  printf '%s\n' 'module.exports = "SHELF";' > node_modules/shelf-labels/prefix.cjs

  cat > show.mjs <<'JS'
import label from "shelf-labels";
console.log(label);
JS
  cat > show.cjs <<'JS'
console.log(require("shelf-labels"));
console.log(require("shelf-labels/prefix"));

try {
  require("shelf-labels/prefix.cjs");
  throw new Error("Unlisted subpath was loaded");
} catch (error) {
  if (error.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
  console.log(error.code);
}
JS
  node show.mjs
  node show.cjs
)

Expected output#

Text
label from ESM
label from CommonJS
SHELF
ERR_PACKAGE_PATH_NOT_EXPORTED

Common mistakes#

Put default last because it always matches. When both exports and main are present, exports takes precedence. Before adding it to an existing package, list the subpaths you intend to keep public. Consumers using an unlisted subpath can get ERR_PACKAGE_PATH_NOT_EXPORTED even when the corresponding file exists.

Version applicability#

Node.js 12.7.0 introduced exports and subpath mappings. The complete example uses conditional exports without experimental flags, available from 12.17.0 in the 12.x line and 13.7.0 in the 13.x line.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0