package.json is one JSON
object. The first table lists every field in npm’s documentation (npm 11), in its
order; the later sections cover version ranges, lifecycle scripts and the fields that
Node.js and other tools read.
Sources: npm 11’s package.json and scripts pages; the node-semver README for range expansions; Node.js’s Modules: Packages; the Corepack README; TypeScript’s Publishing handbook page and its modules reference. The source code of npm’s libraries was read for what the documentation leaves open: npm-package-arg, hosted-git-info, npm-install-checks, validate-npm-package-name and normalize-package-data.
npm fields
| Field | Type | Meaning |
|---|---|---|
name | string | Package name; required to publish. At most 214 characters including a scope (@scope/name); new names lower case and URL-safe; an unscoped name may not start with . or _. Where npm checks it (validate-npm-package-name) a name is an error if it is empty, starts with ., - or _, has leading or trailing spaces, is node_modules or favicon.ico in any letter case, has a scoped name whose package part starts with . (a package part starting with _ is not an error), or has characters that are not URL-friendly (these set validForOldPackages and validForNewPackages both to false); it is only a warning (validForOldPackages stays true, validForNewPackages becomes false) if it has more than 214 characters, capital letters, any of ~'!()* in its last part, or is the name of a Node.js core module. |
version | string | Semantic version that node-semver can parse; required to publish. Name and version together identify a release. npm reads it loosely (normalize-package-data, fixVersionField: “allow ‘loose’ semver 1.0 versions in non-strict mode”) and then replaces it with the cleaned form, so =1.0.0, v1.0.0, 1.0.0beta (a pre-release without its hyphen) and 01.0.0 are accepted and become 1.0.0, 1.0.0, 1.0.0-beta and 1.0.0; the build metadata after + is dropped. A version longer than 256 characters, with a number above 253−1, or that the loose rules do not match (1.0, latest) is refused. |
description | string | Short summary, shown by npm search. |
keywords | array of strings | Search terms. |
homepage | string | Project home page URL. |
bugs | object or string | Issue tracker: { "url", "email" }; a string is the URL. |
license | string | An SPDX licence expression, SEE LICENSE IN <file>, or UNLICENSED. The old object form and licenses array are deprecated. SPDX’s list of identifiers: Licenses… |
author | person | { "name", "email", "url" }, or one string Name <email> (url). |
contributors | array of persons | Other people, in the same forms. (npm sets maintainers itself.) |
funding | object, string or array | Where to fund the project: { "type", "url" } or a URL; shown by npm fund. |
files | array of patterns | What goes into the published tarball (default: everything). Always included, and always left out unless a pattern names them: see the exact lists below. A .npmignore file at the package root does not override files, but in a subfolder it does; without a .npmignore, the .gitignore is used instead. |
exports | object, string or array | Entry points, with conditions (see Node.js fields and conditions and targets). Only listed paths can be imported. |
main | string | Main module; default index.js. |
type | string | How Node.js treats .js files: "module" (ES modules) or "commonjs" (default). npm ignores it. |
browser | string | Entry point for browser bundles. |
bin | object or string | Command names mapped to files, linked onto the PATH on install; a string uses the package name as the command. Files start #!/usr/bin/env node. Installed globally, the file is either linked inside the global bin folder or, on Windows, npm creates a cmd (Windows Command File) that runs it, so the command is available as name or name.cmd in PowerShell. Installed as a dependency, the file is linked where the dependent package can run it with npm exec or by name in its scripts. |
man | string or array | Man page files, names ending in a section number (optionally .gz). A single file is the page for man <pkgname> whatever its name; a file name that does not start with the package name is prefixed with it (./man/bar.1 in package foo becomes man foo-bar); the number is the man section (man 2 foo). As of npm v12, man pages are no longer registered with the system man program: the field is kept for compatibility with package metadata and tools that read it, man <pkgname> will not work after a global install, and npm help <pkgname> is the replacement where supported. |
directories | object | bin: every file in the folder is a command (not with bin); man: every page in the folder (sugar that builds the man array by walking the folder). Setting both bin and directories.bin is an error. As for man, as of npm v12 these pages are no longer installed into the system man path. |
repository | object or string | { "type": "git", "url", "directory" }; shorthands user/repo, github:, gist:, bitbucket:, gitlab: are normalised on publish: npm rewrites the field to the full object form with a url, and if a shorthand (such as "npm/example") was used it prints a warning during npm publish saying the field was auto-corrected. The shorthand still works, but the documentation recommends the full object form ({ "type": "git", "url": "git+https://github.com/npm/example.git" }); npm pkg fix converts a shorthand to it. In a monorepo, directory names the folder that holds the package.json. |
scripts | object | Script names mapped to shell commands; see scripts. |
gypfile | boolean | false stops npm building a binding.gyp native add-on automatically. |
config | object | Values given to scripts as npm_package_config_<key> environment variables. |
dependencies | object | Names mapped to version specs; needed at run time. |
devDependencies | object | Needed only for development; installed only in the root project. |
peerDependencies | object | Host packages this one works with; installed automatically since npm 7. |
peerDependenciesMeta | object | Per peer: { "optional": true } stops it being installed automatically. |
bundleDependencies | array or boolean | Dependencies packed inside the tarball; true means all. bundledDependencies is accepted too. |
optionalDependencies | object | Like dependencies, but installation goes on if one fails. Overrides an entry of the same name in dependencies. |
overrides | object | Forces versions of packages deep in the tree; root project only. Values are specs, $name (the version of a direct dependency) or replacements; keys can nest by parent and carry a version, e.g. "foo@1". The rules, including the "." key and EOVERRIDE, are below. |
engines | object | Ranges of node and npm needed; advisory unless engine-strict is set. |
os | array of strings | Supported process.platform values; !name excludes one; it is allowed (though pointless) to both block and allow an item. npm’s own check (npm-install-checks, checkList) also takes one string as a list of one, and the npm documentation’s libc example is "os": "linux"; the list ["any"] matches everything. A value matches when none of the ! values equals the host’s and, if there are allowed values, one of them equals it. |
cpu | array of strings | Supported process.arch values; !name excludes one; a single string works as for os. |
libc | string | libc the package needs, e.g. glibc; applies only when os is linux. The same check as os is applied to it, so a list works too; npm fails the check when the host’s libc cannot be determined. |
devEngines | object | What developers of the package need: cpu, os, libc, runtime, packageManager, each { "name", "version", "onFail" } (or an array of them) with onFail warn, error (default) or ignore. Checked before install, ci and run. Defaults and the npm rules are below. |
private | boolean | true: npm refuses to publish it. Node.js reads the same field too: see Node.js and other tools. |
publishConfig | object | Settings used when publishing, such as registry, tag, access. |
workspaces | array of strings | Folders or globs of workspace packages, linked into the root node_modules. |
packageExtensions | object | Root only: repairs to the manifests of third-party dependencies before npm resolves the tree, keyed by package selector. Details below. |
Defaults npm fills in: a start script of node server.js
when that file exists; an install script of node-gyp rebuild
when binding.gyp exists and there is no install or
preinstall; contributors from an AUTHORS file at the package root, in which npm reads each line as Name <email> (url), where the email and the url are optional; lines that start with #, and blank lines, are ignored.
Version specs
| Form | Example | Matches |
|---|---|---|
| Exact | 1.2.3 | Only that version. |
| Comparison | >1.2.3, >=, <, <= | The bound. |
| Tilde | ~1.2.3, ~1.2, ~1 | >=1.2.3 <1.3.0-0; >=1.2.0 <1.3.0-0; >=1.0.0 <2.0.0-0. |
| Caret | ^1.2.3, ^0.2.3, ^0.0.3 | >=1.2.3 <2.0.0-0; >=0.2.3 <0.3.0-0; >=0.0.3 <0.0.4-0. |
| X-range | 1.2.x, 1.x, *, "" | >=1.2.0 <1.3.0-0; >=1.0.0 <2.0.0-0; >=0.0.0 (by default not pre-releases); the empty string is the same as *. |
| Hyphen range | 1.2.3 - 2.3.4 | >=1.2.3 <=2.3.4. |
| Union | 1.2.7 || >=1.2.9 <2.0.0 | Matches if every comparator of at least one ||-separated set matches. |
| Dist-tag | latest, next | The version that tag points to. |
| Tarball URL | https://…/pkg.tgz | That tarball. |
| Git URL | git+https://…/repo.git#v1.0.0 | Protocols git, git+ssh, git+http, git+https, git+file; #commit-ish or #semver:<range>. Full form and build triggers below. |
| GitHub shorthand | user/repo#branch | A GitHub repository. |
| Local path | file:../lib | A folder; ../, ~/, ./ and / become file:. The documentation lists path/path/path as a form too: npm-package-arg reads any spec that has a slash and is neither a URL nor user/repo as a path (foo/bar/baz), and a name ending .tgz, .tar.gz or .tar as a file. A spec that starts with a letter and a colon (C:/x, C:\x) is a file spec too: its isFileSpec tests [a-zA-Z]: on every platform. A linked folder does not get its own dependencies installed; run npm install inside it. |
| Alias | npm:other@^1.0.0 | Another package installed under this name. |
Loose reading. npm-package-arg
tests a registry spec with semver.valid(spec, true) and
semver.validRange(spec, true), the loose option of node-semver (its
internal/re.js has the strict and the loose expressions side by side). The loose rules accept
numbers with leading zeros (01.2.3), a pre-release without its hyphen
(1.2.3beta, ^1.0.0rc1) and numeric pre-release identifiers with leading zeros;
the range reading turns them into the normal form (^1.0.0rc1 is
>=1.0.0-rc1 <2.0.0-0). A v or = in front of a version
(v=1.2.3) is accepted by the strict range expression too. A comparator that the loose rules
cannot read is dropped from its set, and the spec fails only if nothing is left. x.x.x is not a
dist-tag: it is read as the range *.
Git URLs as dependencies
The form, from the npm documentation:
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]
<protocol> is one of git, git+ssh, git+http,
git+https or git+file. With #<commit-ish> npm clones exactly
that commit; with #semver:<semver> (any range or exact version) it looks for tags or
refs in the remote repository that match, as for a registry dependency; with neither it uses the
default branch. Examples from the documentation:
git+ssh://git@github.com:npm/cli.git#v1.0.27,
git+ssh://git@github.com:npm/cli#semver:^5.0,
git+https://isaacs@github.com/npm/cli.git,
git://github.com/npm/cli.git#v1.0.27.
The code is wider than that list: npm-package-arg also accepts git+rsync: and
git+ftp: URLs, and hosted-git-info reads ssh:// URLs for the hosts it knows
(github.com, gist.github.com, bitbucket.org, gitlab.com, git.sr.ht); any other URL protocol
stops npm with EUNSUPPORTEDPROTOCOL. A git+ssh://git@host:user/project.git
spec in scp style (a colon, not a port, after the host) is read as a Git URL too.
Build triggers. Installing from a Git repository makes npm clone it into a
temporary folder, install all its dependencies, run the relevant scripts, then pack and install the
resulting folder. That happens when the dependency uses workspaces, or has any of the
scripts build, prepare, prepack, preinstall,
install or postinstall. A repository that holds pre-built files should
define none of them, or it is rebuilt on every installation.
files: the exact lists
Always included, whatever files says: package.json; README and
LICENSE / LICENCE (any case and extension); the file named by
main; the file or files named by bin. Without a files field the
default is ["*"], which includes everything.
Always ignored by default (18 entries): *.orig, .*.swp,
.DS_Store, ._*, .git, .hg,
.lock-wscript, .npmrc, .svn, .wafpickle-N,
CVS, config.gypi, node_modules, npm-debug.log,
package-lock.json, pnpm-lock.yaml, yarn.lock,
bun.lockb.
Most of these can be included by naming them in the files globs. These seven cannot be
included at all: .git, .npmrc, node_modules,
package-lock.json, pnpm-lock.yaml, yarn.lock,
bun.lockb. Patterns follow a syntax similar to .gitignore but
reversed: naming a file, folder or glob includes it.
overrides
Only the root package.json of a project is read for overrides; those in installed
dependencies, workspaces included, are not considered. A value is any specifier npm accepts for a
dependency (an exact version, a range, a dist-tag, or a replacement such as npm:,
file: or a Git URL), the reference $name to the spec of a direct
dependency, or an object.
| Form | Example | Meaning |
|---|---|---|
| Everywhere | "@npm/foo": "1.0.0" | That package at any depth is version 1.0.0. |
Object form with "." | "@npm/foo": { ".": "1.0.0", "@npm/bar": "1.0.0" } | The "." key overrides the package itself; the other keys override packages at any depth below it. |
| Nested | "@npm/bar": { "@npm/foo": "1.0.0" } | @npm/foo is 1.0.0 only below @npm/bar; keys nest to any depth. |
| Version or range in the key | "@npm/bar@2.0.0": { "@npm/foo": "1.0.0" } | Applies only below that version or range of the parent. |
| Reference | "@npm/foo": "$foo" | Uses the spec of the direct dependency foo; that package need not be the one overridden. |
| Fork | "package-name": "npm:@scope/forked-package@1.0.0", "github:username/repo#branch-name", "file:../local-fork" | Replaces the package by another one; works at the top level and nested. |
EOVERRIDE. An override for a package that the project depends on directly is
allowed only if the dependency and the override have exactly the same spec; otherwise npm throws
an EOVERRIDE error. Writing the override as $name, a reference to that
dependency, avoids it.
packageExtensions
Small, declarative repairs to the manifests of third-party dependencies, applied before npm resolves
the dependency tree: add a missing dependencies, optionalDependencies or
peerDependencies entry, or correct peerDependencies and
peerDependenciesMeta. It complements overrides, which changes what an
existing edge resolves to; packageExtensions adds the metadata that creates the edge. It
matters most with install-strategy=linked, where a package sees only what it declared.
- Only honoured in the root
package.json(the workspace root in a workspace); ignored in installed dependencies and in non-root workspace packages. - npm refuses to publish a non-private package that contains it; private packages and unpublished local projects may have it.
- Each key is a package selector: a name with an optional semver range.
"foo"matches all versions,"foo@1"versions satisfying1,"@scope/foo@^2.3.0"versions satisfying^2.3.0. Selectors match the candidate’s own name and version; dist-tags, git, file, directory, URL andnpm:specs are not accepted; for an alias the selector matches the underlying package name. If two selectors match one package the install fails. - Only
dependencies,optionalDependencies,peerDependenciesandpeerDependenciesMetamay be extended.dependenciesandoptionalDependenciesadd a missing dependency only (naming one the package already declares in either field is an error; useoverrides);peerDependenciesare merged by name, replacing an existing range;peerDependenciesMetais merged by name and then by key, and every entry must have apeerDependenciesentry. - Deletion is not supported: a
null,falseor"-"value is an error. - The installed package’s
package.jsonis not rewritten on disk andbundleDependenciesis not changed. Affected packages are recorded inpackage-lock.jsonand shown bynpm explainandnpm ls.
{
"packageExtensions": {
"broken-package@1": { "dependencies": { "missing-runtime-dep": "^2.0.0" } },
"typescript-plugin@4.3.0": {
"peerDependencies": { "typescript": ">=5" },
"peerDependenciesMeta": { "typescript": { "optional": true } }
}
}
}
devEngines
Aids engineers working on a codebase to use the same tooling; it is checked before install,
ci and run. It differs from engines in shape and in use:
engines alerts the user when a dependency needs another npm or node version,
devEngines alerts people working on the source of the project.
- Supported keys:
cpu,os,libc,runtime,packageManager. Each is an object or an array of objects. - An object must have
nameand may haveversionandonFail.onFailiswarn,errororignore; if left undefined it has the same value aserror. - npm assumes that it is running with
node. Ifruntime.nameorpackageManager.nameis any other string, the check fails within the npm CLI. The documentation’s example is{ "runtime": { "name": "node", "onFail": "error" }, "packageManager": { "name": "npm", "onFail": "error" } }. - Corepack reads
devEngines.packageManagertoo: withonFailignoreit prints nothing, unset orerrorit throws on a mismatch,warn(or any other value) prints a warning; if the top-levelpackageManageris missing it uses the manager defined here, preferably with an exact version and hash. - When
devEngines.packageManager.versionis a range rather than a specific version, Corepack resolves it the same way as a range given on the command line: the latest version matching the range is looked up on the npm registry, so the resolution needs network access (or a cache holding a matching version) and may change over time. SettingCOREPACK_ENABLE_AUTO_PIN=1makes Corepack add the resolved version to thepackageManagerfield. When the version is missing, Corepack falls back to its Known Good Release for that package manager (Corepack README).
Scripts
Any name can be run with npm run <name>, and a script named
pre<name> or post<name> runs before or after it.
npm runs these by itself:
| Command | Scripts run, in order |
|---|---|
npm install, npm ci | preinstall, install, postinstall, prepublish, preprepare, prepare, postprepare |
npm rebuild | preinstall, install, postinstall, then prepare only if the folder is a symbolic link |
npm cache add, npm diff | prepare |
npm pack | prepack, prepare, postpack |
npm publish | prepublishOnly, prepack, prepare, postpack, publish, postpublish |
npm test | pretest, test, posttest |
npm start | prestart, start, poststart |
npm stop | prestop, stop, poststop |
npm restart | prerestart, restart, postrestart; with no restart script, stop then start |
npm version | preversion, version, postversion |
After node_modules changes (not in global mode) | dependencies |
prepublish is deprecated and does not run on publish. prepack
also runs when a Git dependency is installed.
prepare (since npm 4.0.0) runs before the package is packed (npm publish,
npm pack), after prepublishOnly and prepack and before
postpack; on a local npm install without package arguments (also with
--production or --omit=dev) but not on npm install express;
and for a package installed as a link through npm install <folder>. If a package
installed through Git has a prepare script, its dependencies and devDependencies are
installed and the script is run before it is packed and installed. From npm 7 these scripts run in
the background (--foreground-scripts shows the output), and in workspaces
prepare scripts run concurrently across all packages; for packages that must build in
order, --foreground-scripts runs them one at a time. preinstall runs before
any dependency is fetched or unpacked into node_modules, so scripts cannot rely on
installed packages (use install or postinstall); for npm ci it
fires after the lock file has been validated against package.json and after
node_modules is wiped.
No uninstall scripts
npm v6 had uninstall lifecycle scripts; npm v7 and later do not. A package can be removed for
many reasons (a user uninstalled it, or a dependent package, or another package still needs this version, or
it was merged as a duplicate with another version), and there is no way to give the script enough context, so
uninstall lifecycle scripts are not implemented and will not function.
Working directory
Scripts always run from the root of the package folder, whatever the current directory is when
npm is invoked. The environment variable INIT_CWD holds the full path of the
directory you were in when you ran npm run. For npm v6 and earlier there were rare cases where
the root was not guaranteed; a package that must support such old versions may check
process.cwd().
Environment
Executables of the dependencies (node_modules/.bin) are added to the PATH. npm
sets these variables from the package.json:
| Variable | Value |
|---|---|
npm_package_name, npm_package_version | The package name and version. |
npm_package_bin_* | Each executable defined in bin. |
npm_package_engines_* | Each engine defined in engines. |
npm_package_config_* | Each value defined in config. |
npm_package_json | The full path to the package.json. |
npm_package_scripts_* | Objects are flattened in this format: {"scripts":{"install":"foo.js"}} gives process.env.npm_package_scripts_install === "foo.js". |
npm_lifecycle_event | The stage of the cycle being executed, so one script can serve several stages. |
npm_old_version, npm_new_version | For preversion, version and postversion: the version before and after the bump. |
npm_package_resolved, npm_package_integrity | For preinstall, install and postinstall: the resolved URL and the integrity hash of the package. |
npm_package_optional, npm_package_dev, npm_package_peer, npm_package_dev_optional | For install scripts: "true" if the package is optional, a dev dependency, a peer dependency, or both dev and optional. |
In npm 7 and later most package.json fields are no longer provided as environment variables;
a script that needs another field reads the file, whose path is in npm_package_json. The
configuration page adds that npm sets its own npm_config_* variables inside scripts (the
configuration parameters, with underscores for dashes, such as
npm_config_allow_same_version), and that Node prefers those lowercase names over any uppercase
NPM_CONFIG_* that you set. In the other direction, any npm_config_* variable in the
environment is read as a configuration parameter.
Exiting
A script line is passed as an argument to /bin/sh on POSIX systems or to
cmd.exe on Windows; the script-shell configuration option chooses another shell.
If the script exits with a code other than 0, the process is aborted. The files a script runs need not be
JavaScript, only some kind of executable file. The documentation advises not to exit with a non-zero code
unless you really mean it: for a minor failure or one that only prevents optional features, print a warning
and exit successfully.
Node.js and other tools
| Field | Read by | Meaning |
|---|---|---|
name, main | Node.js | name is used for self-reference imports; main (a path) is the entry point when the package is imported by name through a node_modules lookup. When exports exists it takes precedence over main for importing by name. main is also the script used when a package directory is loaded through require() (require('./path/to/directory') resolves to ./path/to/directory/index.js by default; see folders as modules in the Node.js CommonJS page). Self-referencing is available only if package.json has exports, and it allows importing only what exports allows. |
private | Node.js | Type boolean. true marks the package as not for publication, signalling to package managers such as npm that it must not be published to a public registry. Node.js uses it for one thing, the experimental flag --experimental-strip-private-modules (Stability 1, Experimental): by default Node.js refuses to strip types from TypeScript files inside a node_modules folder, and with the flag it allows it for files that are not under node_modules and for files in a package whose package.json has "private": true. Only the package.json at the package root is considered, the directory directly under node_modules (or under node_modules/<@scope> for a scoped package); nested package.json files are ignored. Files of a package that is not private still throw ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING. The Node.js documentation says the limitation to private packages should never be lifted, because publishing packages with TypeScript sources is highly discouraged; stripping inside node_modules is meant only for local development. |
exports | Node.js | Type Object | string | string[]. Entry points; when present, only these can be loaded. Subpath keys may use *, a plain string replacement ("./features/*.js": "./src/features/*.js"), and a null target excludes a subpath. Values may be objects of conditions, earlier keys winning. The conditions, the target rules, fallback arrays and nesting are in exports: conditions and targets below. |
imports | Node.js | Type Object. Imports for the package’s own modules; keys must start with # (since Node.js 25.4 and 24.14 also #/), and targets may be external packages. Otherwise the rules are those of exports. |
type | Node.js | Type string. "module": .js files (and files they import) are ES modules; a package.json that lacks type or has "commonjs" gives CommonJS. The nearest package.json up to a node_modules folder or the volume root decides; if the volume root is reached and no package.json is found, .js files are CommonJS. .mjs and .cjs are always ES module and CommonJS. The Node.js page defines only "module" and "commonjs" and says nothing about any other value, so the viewer warns about another value rather than reporting an error. |
packageManager | Corepack | name@x.y.z, required, with name one of yarn, npm or pnpm (Corepack’s permitted values); the hash is optional but strongly recommended as a security practice: "yarn@3.2.3+sha224.953c8233f7a92884eee2de69a1b92d1f2ec1655e66d08071ba9a02fa" (the SHA-224 hash of that version). Instead of a version it can be a URL to a .js file (read as a CommonJS module) or a .tgz file (read as a package; its bin field names the file), with the hash after #: "yarn@https://registry.npmjs.org/@yarnpkg/cli-dist/-/cli-dist-3.2.3.tgz#sha224.16a0…". If packageManager is missing, Corepack uses devEngines.packageManager. |
types (synonym typings) | TypeScript | The main declaration file, e.g. "./lib/main.d.ts", next to main. When exports is not read (compiler options, no exports, or a directory module) and the specifier has no subpath, TypeScript tries types, then typings (legacy), then main with file-extension substitution. Publishing a typed package should include types even where it is not needed, because npm shows a TypeScript icon on the registry listing only if package.json has a types field. In exports, TypeScript always matches the "types" and "default" conditions, and a versioned condition "types@{selector}" using the same selectors as typesVersions. |
typesVersions | TypeScript | An object whose keys are node-semver ranges of the TypeScript version and whose values map path patterns to arrays of substitutions: { ">=3.1": { "*": ["ts3.1/*"] } }, or for one file { "<4.0": { "index.d.ts": ["index.v3.d.ts"] } }. TypeScript reads it first, and the first matching range wins, so order matters (">=3.2" must come before ">=3.1"). If no range matches it falls back to types. It affects only the external API of a package, and is not read where exports is read. A failed lookup through it falls back to package-relative file paths. |
exports: conditions and targets
From Node.js’s “Modules: Packages”. exports is an object, a string
(sugar for { ".": "…" }) or an array of targets. In an object, keys are either all
subpaths ("." or starting ./) or all conditions.
Conditions
Node.js implements these, listed from most to least specific, which is how they should be ordered. Key order is significant: earlier entries take precedence.
| Condition | Matches |
|---|---|
"node-addons" | Like "node": any Node.js environment; for an entry point that uses native C++ addons. Can be switched off with --no-addons, so treat "default" as a more universal fallback (for example WebAssembly). |
"node" | Any Node.js environment; CommonJS or ES module file. |
"import" | The package is loaded by import or import(), or any top-level import or resolve of the ES module loader, whatever the target file’s format. Always mutually exclusive with "require". |
"require" | The package is loaded by require(); the file should be loadable that way (CommonJS, JSON, native addons and ES modules). Always mutually exclusive with "import". |
"module-sync" | Whether loaded by import, import() or require(); the format is an ES module without top-level await in its graph, otherwise ERR_REQUIRE_ASYNC_MODULE is thrown on require(). |
"worker" | The package is loaded inside a Web Worker thread, including the worker entry point, all its dependencies, import(), require() and import.meta.resolve(). Not threads made with node:worker_threads, even from inside a Web Worker. |
"default" | The generic fallback that always matches; should always come last. |
"import" and "require" are siblings: Node.js lists them as two separate
conditions that never both match, not as one nested inside the other. Other condition strings are
ignored by default; they can be enabled with --conditions (-C). The
community conditions Node.js lists to coordinate the ecosystem:
"types": typing systems resolve the typing file for the export; always include it first."browser": any web browser environment."development": a development-only entry point, for example with better error messages. Must always be mutually exclusive with"production"."production": a production entry point. Must always be mutually exclusive with"development".
Platform conditions for other runtimes are kept in WinterCG’s Runtime Keys proposal. When
branching by environment, include "default" where possible; "node" with
"default" is usually better than "node" with "browser".
Limits on condition names
Typical conditions use only letters and digits, with :, - or = as
separators. In Node.js a condition (1) must contain at least one character, (2) cannot start with
. because it may appear where relative paths are allowed, (3) cannot contain
, because some CLI tools read a comma-separated list, and (4) cannot be an integer
property key such as "10", because that changes the order of the keys of a JavaScript
object.
Nested conditions and fallback arrays
A condition’s value may be another condition object. Conditions are matched in order as in flat
objects; if a nested object has no matching condition, checking continues with the remaining
conditions of the parent, like nested if statements:
{ "exports": { "node": { "import": "./feature-node.mjs", "require": "./feature-node.cjs" }, "default": "./feature.mjs" } }
Anywhere a target is accepted in exports or imports, an array of targets can be
used. Node.js tries the items in order and uses the first valid target. An item is skipped only when it
is not a valid target (for example a string that breaks the path rules below) or is a conditions object
in which no condition matches. Node.js does not check that the file exists: once an item is a valid
target the rest is ignored even if loading then fails, so ["./src/feature.js",
"./dist/feature.js"] always resolves to the first. An empty array exports nothing; if every item
is invalid, the error for the last item is thrown.
Rules for targets
Every target (the values of exports) is a relative URL string starting with
./: "/dist/main.js", "file:///dev/null" and
"../common/util.js" are all invalid. A target must not resolve outside the package
directory, and after the initial ./ (and in any subpath substituted into a pattern) the
segments ., .. and node_modules, and their URL-encoded forms,
are generally disallowed: "./dist/../../elsewhere/file.js",
"././dist/main.js" and "./dist/../dist/main.js" are invalid, and so is a
key such as "./utils/./helper.js". imports differs only in that its targets
may be external package names. Patterns use * as plain string replacement of every
* on the right-hand side, including across /; Node.js’s page says
nothing about a key with more than one *. Including *.js on both sides of the
mapping restricts the exposed exports to JS files.
Encapsulation
When exports is defined, all subpaths of the package are encapsulated and no longer
available to importers: require('pkg/subpath.js') throws
ERR_PACKAGE_PATH_NOT_EXPORTED. That includes the package.json itself, so
require('pkg/package.json') fails unless "./package.json" is listed, which is why
adding exports to an existing package will likely be a breaking change. The encapsulation is not a
strong encapsulation: a direct require of an absolute path inside the package, such as
require('/path/to/node_modules/pkg/subpath.js'), still loads the file. A value of
exports that is not an object, an array or a string (null, a number, a boolean) is
ignored by Node.js’s package.json reader, which then loads the package through main.