GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing nodejs.org — Modules: Packages | Node.js v26.13.1 Documentation Skip to content
Modules: Packages#History
Introduction#A package is a folder tree described by a This page provides guidance for package authors writing Determining module system#Introduction#Node.js will treat the following as ES modules when passed to
Node.js will treat the following as CommonJS when passed to
Writing ES module syntax in "ambiguous" files incurs a performance cost, and
therefore it is encouraged that authors be explicit wherever possible. In
particular, package authors should always include the Syntax detection#Added in: v21.1.0, v20.10.0 History
Stability: 1.2 - Release candidate Node.js will inspect the source code of ambiguous input to determine whether it contains ES module syntax; if such syntax is detected, the input will be treated as an ES module. Ambiguous input is defined as:
ES module syntax is defined as syntax that would throw when evaluated as CommonJS. This includes the following:
Module resolution and loading#Node.js has two types of module resolution and loading, chosen based on how the module is requested. When a module is requested via
When a module is requested via static
Regardless of how a module is requested, the resolution and loading process can be customized using customization hooks.
|
| Version | Changes |
|---|---|
| v25.4.0, v24.14.0 | Allow subpath imports that start with |
In addition to the "exports" field, there is a package "imports" field
to create private mappings that only apply to import specifiers from within the
package itself.
Entries in the "imports" field must always start with # to ensure they are
disambiguated from external package specifiers.
For example, the imports field can be used to gain the benefits of conditional exports for internal modules:
// package.json { "imports": { "#dep": { "node": "dep-node-native", "default": "./dep-polyfill.js" } }, "dependencies": { "dep-node-native": "^1.0.0" } }json
where import '#dep' does not get the resolution of the external package
dep-node-native (including its exports in turn), and instead gets the local
file ./dep-polyfill.js relative to the package in other environments.
Unlike the "exports" field, the "imports" field permits mapping to external
packages.
The resolution rules for the imports field are otherwise analogous to the exports field.
| Version | Changes |
|---|---|
| v16.10.0, v14.19.0 | Support pattern trailers in "imports" field. |
| v16.9.0, v14.19.0 | Support pattern trailers. |
For packages with a small number of exports or imports, we recommend
explicitly listing each exports subpath entry. But for packages that have
large numbers of subpaths, this might cause package.json bloat and
maintenance issues.
For these use cases, subpath export patterns can be used instead:
// ./node_modules/es-module-package/package.json { "exports": { "./features/*.js": "./src/features/*.js" }, "imports": { "#internal/*.js": "./src/internal/*.js" } }json
* maps expose nested subpaths as it is a string replacement syntax
only.
All instances of * on the right hand side will then be replaced with this
value, including if it contains any / separators.
import featureX from 'es-module-package/features/x.js'; // Loads ./node_modules/es-module-package/src/features/x.js import featureY from 'es-module-package/features/y/y.js'; // Loads ./node_modules/es-module-package/src/features/y/y.js import internalZ from '#internal/z.js'; // Loads ./src/internal/z.jsjs
This is a direct static matching and replacement without any special handling
for file extensions. Including the "*.js" on both sides of the mapping
restricts the exposed package exports to only JS files.
The property of exports being statically enumerable is maintained with exports
patterns since the individual exports for a package can be determined by
treating the right hand side target pattern as a ** glob against the list of
files within the package. Because node_modules paths are forbidden in exports
targets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, null targets can be used:
// ./node_modules/es-module-package/package.json { "exports": { "./features/*.js": "./src/features/*.js", "./features/private-internal/*": null } }json
import featureInternal from 'es-module-package/features/private-internal/m.js'; // Throws: ERR_PACKAGE_PATH_NOT_EXPORTED import featureX from 'es-module-package/features/x.js'; // Loads ./node_modules/es-module-package/src/features/x.jsjs
| Version | Changes |
|---|---|
| v13.7.0, v12.16.0 | Unflag conditional exports. |
Conditional exports provide a way to map to different paths depending on certain conditions. They are supported for both CommonJS and ES module imports.
For example, a package that wants to provide different ES module exports for
require() and import can be written:
// package.json { "exports": { "import": "./index-module.js", "require": "./index-require.cjs" }, "type": "module" }json
Node.js implements the following conditions, listed in order from most specific to least specific as conditions should be defined:
"node-addons" - similar to "node" and matches for any Node.js environment.
This condition can be used to provide an entry point which uses native C++
addons as opposed to an entry point which is more universal and doesn't rely
on native addons. This condition can be disabled via the
--no-addons flag."node" - matches for any Node.js environment. Can be a CommonJS or ES
module file. In most cases explicitly calling out the Node.js platform is
not necessary."import" - matches when the package is loaded via import or
import(), or via any top-level import or resolve operation by the
ECMAScript module loader. Applies regardless of the module format of the
target file. Always mutually exclusive with "require"."require" - matches when the package is loaded via require(). The
referenced file should be loadable with require() although the condition
matches regardless of the module format of the target file. Expected
formats include CommonJS, JSON, native addons, and ES modules. Always mutually
exclusive with "import"."module-sync" - matches no matter the package is loaded via import,
import() or require(). The format is expected to be ES modules that does
not contain top-level await in its module graph - if it does,
ERR_REQUIRE_ASYNC_MODULE will be thrown when the module is require()-ed."default" - the generic fallback that always matches. Can be a CommonJS
or ES module file. This condition should always come last.Within the "exports" object, key order is significant. During condition
matching, earlier entries have higher priority and take precedence over later
entries. The general rule is that conditions should be from most specific to
least specific in object order.
Using the "import" and "require" conditions can lead to some hazards,
which are further explained in the dual CommonJS/ES module packages section.
The "node-addons" condition can be used to provide an entry point which
uses native C++ addons. However, this condition can be disabled via the
--no-addons flag. When using "node-addons", it's recommended to treat
"default" as an enhancement that provides a more universal entry point, e.g.
using WebAssembly instead of a native addon.
Conditional exports can also be extended to exports subpaths, for example:
{ "exports": { ".": "./index.js", "./feature.js": { "node": "./feature-node.js", "default": "./feature.js" } } }json
Defines a package where require('pkg/feature.js') and
import 'pkg/feature.js' could provide different implementations between
Node.js and other JS environments.
When using environment branches, always include a "default" condition where
possible. Providing a "default" condition ensures that any unknown JS
environments are able to use this universal implementation, which helps avoid
these JS environments from having to pretend to be existing environments in
order to support packages with conditional exports. For this reason, using
"node" and "default" condition branches is usually preferable to using
"node" and "browser" condition branches.
In addition to direct mappings, Node.js also supports nested condition objects.
For example, to define a package that only has dual mode entry points for use in Node.js but not the browser:
{ "exports": { "node": { "import": "./feature-node.mjs", "require": "./feature-node.cjs" }, "default": "./feature.mjs" } }json
Conditions continue to be matched in order as with flat conditions. If
a nested condition does not have any mapping it will continue checking
the remaining conditions of the parent condition. In this way nested
conditions behave analogously to nested JavaScript if statements.
When running Node.js, custom user conditions can be added with the
--conditions flag:
node --conditions=development index.jsbash
which would then resolve the "development" condition in package imports and
exports, while resolving the existing "node", "node-addons", "default",
"import", and "require" conditions as appropriate.
Any number of custom conditions can be set with repeat flags.
Typical conditions should only contain alphanumerical characters, using ":", "-", or "=" as separators if necessary. Anything else may run into compatibility issues outside of node.
In node, conditions have very few restrictions, but specifically these include:
Condition strings other than the "import", "require", "node", "module-sync",
"node-addons" and "default" conditions
implemented in Node.js core are ignored by default.
Other platforms may implement other conditions and user conditions can be
enabled in Node.js via the --conditions / -C flag.
Since custom package conditions require clear definitions to ensure correct usage, a list of common known package conditions and their strict definitions is provided below to assist with ecosystem coordination.
"types" - can be used by typing systems to resolve the typing file for
the given export. This condition should always be included first."browser" - any web browser environment."development" - can be used to define a development-only environment
entry point, for example to provide additional debugging context such as
better error messages when running in a development mode. Must always be
mutually exclusive with "production"."production" - can be used to define a production environment entry
point. Must always be mutually exclusive with "development".For other runtimes, platform-specific condition key definitions are maintained by the WinterCG in the Runtime Keys proposal specification.
New conditions definitions may be added to this list by creating a pull request to the Node.js documentation for this section. The requirements for listing a new condition definition here are that:
"types" condition is a good example: It
doesn't really belong in the Runtime Keys proposal but is a good fit
here in the Node.js docs.The above definitions may be moved to a dedicated conditions registry in due course.
| Version | Changes |
|---|---|
| v13.6.0, v12.16.0 | Unflag self-referencing a package using its name. |
Within a package, the values defined in the package's
package.json "exports" field can be referenced via the package's name.
For example, assuming the package.json is:
// package.json { "name": "a-package", "exports": { ".": "./index.mjs", "./foo.js": "./foo.js" } }json
Then any module in that package can reference an export in the package itself:
// ./a-module.mjs import { something } from 'a-package'; // Imports "something" from ./index.mjs.js
Self-referencing is available only if package.json has "exports", and
will allow importing only what that "exports" (in the package.json)
allows. So the code below, given the previous package, will generate a runtime
error:
// ./another-module.mjs // Imports "another" from ./m.mjs. Fails because // the "package.json" "exports" field // does not provide an export named "./m.mjs". import { another } from 'a-package/m.mjs';js
Self-referencing is also available when using require, both in an ES module,
and in a CommonJS one. For example, this code will also work:
// ./a-module.js const { something } = require('a-package/foo.js'); // Loads from ./foo.js.cjs
Finally, self-referencing also works with scoped packages. For example, this code will also work:
// package.json { "name": "@my/package", "exports": "./index.js" }json
// ./index.js module.exports = 42;cjs
// ./other.js console.log(require('@my/package'));cjs
$ node other.js 42console
See the package examples repository for details.
Stability: 1 - Experimental. Enable this API with --experimental-package-map.
Package maps provide a mechanism to control package resolution without relying
on the node_modules folder structure. When enabled via the
--experimental-package-map flag, Node.js uses a JSON configuration file
to determine how bare specifiers are resolved.
This feature is useful for:
The package map configuration file is a JSON file with a packages object.
Each key in packages is called a package ID and is a unique identifier for a package entry:
{ "packages": { "app": { "url": "./packages/app", "dependencies": { "@myorg/utils": "utils", "@myorg/ui-lib": "ui-lib" } }, "utils": { "url": "./packages/utils" }, "ui-lib": { "url": "./packages/ui-lib", "dependencies": { "@myorg/utils": "utils" } } } }json
Each package entry has the following fields:
url <string> Required. An absolute or relative URL. This is parsed using
the WHATWG URL API, using the configuration file URL as base. Only
file: protocol is supported. Multiple packages are allowed to share the
same URL; consumers must key module instances by both module url and package IDs
to differentiate them.dependencies <Object> An object mapping bare specifiers to package keys.
Each key is the import name used in source code, and each value is the
corresponding package key in the packages object. Defaults to an empty
object.When a bare specifier is encountered:
url.ERR_PACKAGE_MAP_EXTERNAL_FILE error is thrown.dependencies object to find the corresponding package key.url field in the package map.dependencies, a
MODULE_NOT_FOUND error is thrown.index.js, exports field, etc).More details can be found in the resolution algorithm pseudo-code.
Different packages can depend on different versions of the same package.
Because dependencies maps bare specifiers to package keys, two packages
can map the same specifier to different targets:
{ "packages": { "app": { "url": "./app", "dependencies": { "component": "component-v2" } }, "legacy": { "url": "./legacy", "dependencies": { "component": "component-v1" } }, "component-v1": { "url": "./vendor/component-1.0.0" }, "component-v2": { "url": "./vendor/component-2.0.0" } } }json
Both app and legacy can import 'component', but they resolve to
different paths based on their declared dependencies.
To address complex hoisting situations, multiple packages may share the same URL, which introduces ambiguity when determining which package an import originates from:
{ "packages": { "app-old": { "url": "./app-old", "dependencies": { "lib": "lib-old" } }, "app-new": { "url": "./app-new", "dependencies": { "lib": "lib-new" } }, "lib-old": { "url": "./lib", "dependencies": { "react": "react-15" } }, "lib-new": { "url": "./lib", "dependencies": { "react": "react-18" } } } }json
In the example above both lib-old and lib-new use the same ./lib folder to
store their sources, the only difference being in which version of react they'll
access when performing require calls or using import.
Because multiple package entries share the same URL, resolving a bare specifier from a file within that URL is ambiguous unless the originating package ID is known. If the package ID cannot be determined (for example, because the caller did not propagate it from a previous resolution), Node.js will throw an error rather than guess.
To support this pattern, implementers must key module instances by package ID
and propagate it from each resolution result to subsequent resolution requests.
This ensures that when lib requires react, the runtime knows whether the
request comes from lib-old or lib-new and can select the correct dependency.
Package maps only apply to bare specifiers that are not Node.js builtin modules. The following cases are not affected by package maps and continue to use standard resolution:
./ or ../).node:fs, etc.).package.json field definitions#This section describes the fields used by the Node.js runtime. Other tools (such as npm) use additional fields which are ignored by Node.js and not documented here.
The following fields in package.json files are used in Node.js:
"name" - Relevant when using named imports within a package. Also used
by package managers as the name of the package."main" - The default module when loading the package, if exports is not
specified, and in versions of Node.js prior to the introduction of exports."type" - The package type determining whether to load .js files as
CommonJS or ES modules."exports" - Package exports and conditional exports. When present,
limits which submodules can be loaded from within the package."imports" - Package imports, for use by modules within the package
itself."name"#| Version | Changes |
|---|---|
| v13.6.0, v12.16.0 | Remove the |
<string>{ "name": "package-name" }json
The "name" field defines your package's name. Publishing to the
npm registry requires a name that satisfies
certain requirements.
The "name" field can be used in addition to the "exports" field to
self-reference a package using its name.
"main"#<string>{ "main": "./index.js" }json
The "main" field defines the entry point of a package when imported by name
via a node_modules lookup. Its value is a path.
The "exports" field, if it exists, takes precedence over the
"main" field when importing the package by name.
It also defines the script that is used when the package directory is loaded
via require().
// This resolves to ./path/to/directory/index.js. require('./path/to/directory');cjs
"type"#| Version | Changes |
|---|---|
| v13.2.0, v12.17.0 | Unflag |
<string>The "type" field defines the module format that Node.js uses for all
.js files that have that package.json file as their nearest parent.
Files ending with .js are loaded as ES modules when the nearest parent
package.json file contains a top-level field "type" with a value of
"module".
The nearest parent package.json is defined as the first package.json found
when searching in the current folder, that folder's parent, and so on up
until a node_modules folder or the volume root is reached.
// package.json { "type": "module" }json
# In same folder as preceding package.json node my-app.js # Runs as ES modulebash
If the nearest parent package.json lacks a "type" field, or contains
"type": "commonjs", .js files are treated as CommonJS. If the volume
root is reached and no package.json is found, .js files are treated as
CommonJS.
import statements of .js files are treated as ES modules if the nearest
parent package.json contains "type": "module".
// my-app.js, part of the same example as above import './startup.js'; // Loaded as ES module because of package.jsonjs
Regardless of the value of the "type" field, .mjs files are always treated
as ES modules and .cjs files are always treated as CommonJS.
"exports"#| Version | Changes |
|---|---|
| v14.13.0, v12.20.0 | Add support for |
| v13.7.0, v12.17.0 | Unflag conditional exports. |
| v13.7.0, v12.16.0 | Implement logical conditional exports ordering. |
| v13.7.0, v12.16.0 | Remove the |
| v13.2.0, v12.16.0 | Implement conditional exports. |
{ "exports": "./index.js" }json
The "exports" field allows defining the entry points of a package when
imported by name loaded either via a node_modules lookup or a
self-reference to its own name. It is supported in Node.js 12+ as an
alternative to the "main" that can support defining subpath exports
and conditional exports while encapsulating internal unexported modules.
Conditional Exports can also be used within "exports" to define different
package entry points per environment, including whether the package is
referenced via require or via import.
All paths defined in the "exports" must be relative file URLs starting with
./.
"imports"#<Object>// package.json { "imports": { "#dep": { "node": "dep-node-native", "default": "./dep-polyfill.js" } }, "dependencies": { "dep-node-native": "^1.0.0" } }json
Entries in the imports field must be strings starting with #.
Package imports permit mapping to external packages.
This field defines subpath imports for the current package.