{ "type": "module", "source": "doc/api/packages.md", "introduced_in": "v12.20.0", "meta": { "changes": [ { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/34117", "description": "Add package `\"imports\"` field." }, { "version": [ "v13.7.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Unflag conditional exports." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Remove the `--experimental-conditional-exports` option. In 12.16.0, conditional exports are still behind `--experimental-modules`." }, { "version": [ "v13.6.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31002", "description": "Unflag self-referencing a package using its name." }, { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28568", "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "miscs": [ { "textRaw": "Modules: Packages", "name": "Modules: Packages", "introduced_in": "v12.20.0", "type": "misc", "meta": { "changes": [ { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/34117", "description": "Add package `\"imports\"` field." }, { "version": [ "v13.7.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Unflag conditional exports." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Remove the `--experimental-conditional-exports` option. In 12.16.0, conditional exports are still behind `--experimental-modules`." }, { "version": [ "v13.6.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31002", "description": "Unflag self-referencing a package using its name." }, { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28568", "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "miscs": [ { "textRaw": "Introduction", "name": "introduction", "desc": "
A package is a folder tree described by a package.json
file. The package\nconsists of the folder containing the package.json
file and all subfolders\nuntil the next folder containing another package.json
file, or a folder\nnamed node_modules
.
This page provides guidance for package authors writing package.json
files\nalong with a reference for the package.json
fields defined by Node.js.
Node.js will treat the following as ES modules when passed to node
as the\ninitial input, or when referenced by import
statements or import()
\nexpressions:
Files with an .mjs
extension.
Files with a .js
extension when the nearest parent package.json
file\ncontains a top-level \"type\"
field with a value of \"module\"
.
Strings passed in as an argument to --eval
, or piped to node
via STDIN
,\nwith the flag --input-type=module
.
Node.js will treat as CommonJS all other forms of input, such as .js
files\nwhere the nearest parent package.json
file contains no top-level \"type\"
\nfield, or string input without the flag --input-type
. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node
as the initial input,\nor when referenced by import
statements, import()
expressions, or\nrequire()
expressions:
Files with a .cjs
extension.
Files with a .js
extension when the nearest parent package.json
file\ncontains a top-level field \"type\"
with a value of \"commonjs\"
.
Strings passed in as an argument to --eval
or --print
, or piped to node
\nvia STDIN
, with the flag --input-type=commonjs
.
Package authors should include the \"type\"
field, even in packages where\nall sources are CommonJS. Being explicit about the type
of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.
Node.js has two systems for resolving a specifier and loading modules.
\nThere is the CommonJS module loader:
\nrequire()
calls..js
, .json
, and finally .node
) and then attempt to resolve\nfolders as modules..json
as JSON text files..node
files are interpreted as compiled addon modules loaded with\nprocess.dlopen()
..json
or .node
extensions as JavaScript\ntext files.There is the ECMAScript module loader:
\nimport
statements and import()
expressions.'./startup/index.js'
) must be fully specified..js
, .mjs
, and .cjs
extensions for JavaScript text\nfiles.cjs-module-lexer
to try to identify named exports,\nwhich are available if they can be determined through static analysis.\nImported CommonJS modules have their URLs converted to absolute\npaths and are then loaded via the CommonJS module loader.Within a package, the package.json
\"type\"
field defines how\nNode.js should interpret .js
files. If a package.json
file does not have a\n\"type\"
field, .js
files are treated as CommonJS.
A package.json
\"type\"
value of \"module\"
tells Node.js to interpret .js
\nfiles within that package as using ES module syntax.
The \"type\"
field applies not only to initial entry points (node my-app.js
)\nbut also to files referenced by import
statements and import()
expressions.
// my-app.js, treated as an ES module because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the \"type\" value from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n
\nFiles ending with .mjs
are always loaded as ES modules regardless of\nthe nearest parent package.json
.
Files ending with .cjs
are always loaded as CommonJS regardless of the\nnearest parent package.json
.
import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n
\nThe .mjs
and .cjs
extensions can be used to mix types within the same\npackage:
Within a \"type\": \"module\"
package, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a .cjs
\nextension (since both .js
and .mjs
files are treated as ES modules within\na \"module\"
package).
Within a \"type\": \"commonjs\"
package, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an .mjs
\nextension (since both .js
and .cjs
files are treated as CommonJS within a\n\"commonjs\"
package).
Strings passed in as an argument to --eval
(or -e
), or piped to node
via\nSTDIN
, are treated as ES modules when the --input-type=module
flag\nis set.
node --input-type=module --eval \"import { sep } from 'node:path'; console.log(sep);\"\n\necho \"import { sep } from 'node:path'; console.log(sep);\" | node --input-type=module\n
\nFor completeness there is also --input-type=commonjs
, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type
is\nunspecified.
While all Node.js projects are expected to be installable by all package\nmanagers once published, their development teams are often required to use one\nspecific package manager. To make this process easier, Node.js ships with a\ntool called Corepack that aims to make all package managers transparently\navailable in your environment - provided you have Node.js installed.
\nBy default Corepack won't enforce any specific package manager and will use\nthe generic \"Last Known Good\" versions associated with each Node.js release,\nbut you can improve this experience by setting the \"packageManager\"
field\nin your project's package.json
.
In a package's package.json
file, two fields can define entry points for a\npackage: \"main\"
and \"exports\"
. Both fields apply to both ES module\nand CommonJS module entry points.
The \"main\"
field is supported in all versions of Node.js, but its\ncapabilities are limited: it only defines the main entry point of the package.
The \"exports\"
provides a modern alternative to \"main\"
allowing\nmultiple entry points to be defined, conditional entry resolution support\nbetween environments, and preventing any other entry points besides those\ndefined in \"exports\"
. This encapsulation allows module authors to\nclearly define the public interface for their package.
For new packages targeting the currently supported versions of Node.js, the\n\"exports\"
field is recommended. For packages supporting Node.js 10 and\nbelow, the \"main\"
field is required. If both \"exports\"
and\n\"main\"
are defined, the \"exports\"
field takes precedence over\n\"main\"
in supported versions of Node.js.
Conditional exports can be used within \"exports\"
to define different\npackage entry points per environment, including whether the package is\nreferenced via require
or via import
. For more information about supporting\nboth CommonJS and ES modules in a single package please consult\nthe dual CommonJS/ES module packages section.
Existing packages introducing the \"exports\"
field will prevent consumers\nof the package from using any entry points that are not defined, including the\npackage.json
(e.g. require('your-package/package.json')
. This will\nlikely be a breaking change.
To make the introduction of \"exports\"
non-breaking, ensure that every\npreviously supported entry point is exported. It is best to explicitly specify\nentry points so that the package's public API is well-defined. For example,\na project that previously exported main
, lib
,\nfeature
, and the package.json
could use the following package.exports
:
{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./lib\": \"./lib/index.js\",\n \"./lib/index\": \"./lib/index.js\",\n \"./lib/index.js\": \"./lib/index.js\",\n \"./feature\": \"./feature/index.js\",\n \"./feature/index\": \"./feature/index.js\",\n \"./feature/index.js\": \"./feature/index.js\",\n \"./package.json\": \"./package.json\"\n }\n}\n
\nAlternatively a project could choose to export entire folders both with and\nwithout extensioned subpaths using export patterns:
\n{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./lib\": \"./lib/index.js\",\n \"./lib/*\": \"./lib/*.js\",\n \"./lib/*.js\": \"./lib/*.js\",\n \"./feature\": \"./feature/index.js\",\n \"./feature/*\": \"./feature/*.js\",\n \"./feature/*.js\": \"./feature/*.js\",\n \"./package.json\": \"./package.json\"\n }\n}\n
\nWith the above providing backwards-compatibility for any minor package versions,\na future major change for the package can then properly restrict the exports\nto only the specific feature exports exposed:
\n{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./feature/*.js\": \"./feature/*.js\",\n \"./feature/internal/*\": null\n }\n}\n
",
"modules": [
{
"textRaw": "Main entry point export",
"name": "main_entry_point_export",
"desc": "When writing a new package, it is recommended to use the \"exports\"
field:
{\n \"exports\": \"./index.js\"\n}\n
\nWhen the \"exports\"
field is defined, all subpaths of the package are\nencapsulated and no longer available to importers. For example,\nrequire('pkg/subpath.js')
throws an ERR_PACKAGE_PATH_NOT_EXPORTED
\nerror.
This encapsulation of exports provides more reliable guarantees\nabout package interfaces for tools and when handling semver upgrades for a\npackage. It is not a strong encapsulation since a direct require of any\nabsolute subpath of the package such as\nrequire('/path/to/node_modules/pkg/subpath.js')
will still load subpath.js
.
All currently supported versions of Node.js and modern build tools support the\n\"exports\"
field. For projects using an older version of Node.js or a related\nbuild tool, compatibility can be achieved by including the \"main\"
field\nalongside \"exports\"
pointing to the same module:
{\n \"main\": \"./index.js\",\n \"exports\": \"./index.js\"\n}\n
",
"type": "module",
"displayName": "Main entry point export"
},
{
"textRaw": "Subpath exports",
"name": "subpath_exports",
"meta": {
"added": [
"v12.7.0"
],
"changes": []
},
"desc": "When using the \"exports\"
field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n\".\"
subpath:
{\n \"exports\": {\n \".\": \"./index.js\",\n \"./submodule.js\": \"./src/submodule.js\"\n }\n}\n
\nNow only the defined subpath in \"exports\"
can be imported by a consumer:
import submodule from 'es-module-package/submodule.js';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\nWhile other subpaths will error:
\nimport submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n
",
"modules": [
{
"textRaw": "Extensions in subpaths",
"name": "extensions_in_subpaths",
"desc": "Package authors should provide either extensioned (import 'pkg/subpath.js'
) or\nextensionless (import 'pkg/subpath'
) subpaths in their exports. This ensures\nthat there is only one subpath for each exported module so that all dependents\nimport the same consistent specifier, keeping the package contract clear for\nconsumers and simplifying package subpath completions.
Traditionally, packages tended to use the extensionless style, which has the\nbenefits of readability and of masking the true path of the file within the\npackage.
\nWith import maps now providing a standard for package resolution in browsers\nand other JavaScript runtimes, using the extensionless style can result in\nbloated import map definitions. Explicit file extensions can avoid this issue by\nenabling the import map to utilize a packages folder mapping to map multiple\nsubpaths where possible instead of a separate map entry per package subpath\nexport. This also mirrors the requirement of using the full specifier path\nin relative and absolute import specifiers.
", "type": "module", "displayName": "Extensions in subpaths" } ], "type": "module", "displayName": "Subpath exports" }, { "textRaw": "Exports sugar", "name": "exports_sugar", "meta": { "added": [ "v12.11.0" ], "changes": [] }, "desc": "If the \".\"
export is the only export, the \"exports\"
field provides sugar\nfor this case being the direct \"exports\"
field value.
{\n \"exports\": {\n \".\": \"./index.js\"\n }\n}\n
\ncan be written:
\n{\n \"exports\": \"./index.js\"\n}\n
",
"type": "module",
"displayName": "Exports sugar"
},
{
"textRaw": "Subpath imports",
"name": "subpath_imports",
"meta": {
"added": [
"v14.6.0",
"v12.19.0"
],
"changes": []
},
"desc": "In addition to the \"exports\"
field, there is a package \"imports\"
field\nto create private mappings that only apply to import specifiers from within the\npackage itself.
Entries in the \"imports\"
field must always start with #
to ensure they are\ndisambiguated from external package specifiers.
For example, the imports field can be used to gain the benefits of conditional\nexports for internal modules:
\n// package.json\n{\n \"imports\": {\n \"#dep\": {\n \"node\": \"dep-node-native\",\n \"default\": \"./dep-polyfill.js\"\n }\n },\n \"dependencies\": {\n \"dep-node-native\": \"^1.0.0\"\n }\n}\n
\nwhere import '#dep'
does not get the resolution of the external package\ndep-node-native
(including its exports in turn), and instead gets the local\nfile ./dep-polyfill.js
relative to the package in other environments.
Unlike the \"exports\"
field, the \"imports\"
field permits mapping to external\npackages.
The resolution rules for the imports field are otherwise analogous to the\nexports field.
", "type": "module", "displayName": "Subpath imports" }, { "textRaw": "Subpath patterns", "name": "subpath_patterns", "meta": { "added": [ "v14.13.0", "v12.20.0" ], "changes": [ { "version": [ "v16.10.0", "v14.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/40041", "description": "Support pattern trailers in \"imports\" field." }, { "version": [ "v16.9.0", "v14.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/39635", "description": "Support pattern trailers." } ] }, "desc": "For packages with a small number of exports or imports, we recommend\nexplicitly listing each exports subpath entry. But for packages that have\nlarge numbers of subpaths, this might cause package.json
bloat and\nmaintenance issues.
For these use cases, subpath export patterns can be used instead:
\n// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./features/*.js\": \"./src/features/*.js\"\n },\n \"imports\": {\n \"#internal/*.js\": \"./src/internal/*.js\"\n }\n}\n
\n*
maps expose nested subpaths as it is a string replacement syntax\nonly.
All instances of *
on the right hand side will then be replaced with this\nvalue, including if it contains any /
separators.
import featureX from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y.js';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z.js';\n// Loads ./node_modules/es-module-package/src/internal/z.js\n
\nThis is a direct static matching and replacement without any special handling\nfor file extensions. Including the \"*.js\"
on both sides of the mapping\nrestricts the exposed package exports to only JS files.
The property of exports being statically enumerable is maintained with exports\npatterns since the individual exports for a package can be determined by\ntreating the right hand side target pattern as a **
glob against the list of\nfiles within the package. Because node_modules
paths are forbidden in exports\ntargets, 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\n{\n \"exports\": {\n \"./features/*.js\": \"./src/features/*.js\",\n \"./features/private-internal/*\": null\n }\n}\n
\nimport featureInternal from 'es-module-package/features/private-internal/m.js';\n// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED\n\nimport featureX from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n
",
"type": "module",
"displayName": "Subpath patterns"
},
{
"textRaw": "Conditional exports",
"name": "conditional_exports",
"meta": {
"added": [
"v13.2.0",
"v12.16.0"
],
"changes": [
{
"version": [
"v13.7.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/31001",
"description": "Unflag conditional exports."
}
]
},
"desc": "Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.
\nFor example, a package that wants to provide different ES module exports for\nrequire()
and import
can be written:
// package.json\n{\n \"exports\": {\n \"import\": \"./index-module.js\",\n \"require\": \"./index-require.cjs\"\n },\n \"type\": \"module\"\n}\n
\nNode.js implements the following conditions, listed in order from most\nspecific to least specific as conditions should be defined:
\n\"node-addons\"
- similar to \"node\"
and matches for any Node.js environment.\nThis condition can be used to provide an entry point which uses native C++\naddons as opposed to an entry point which is more universal and doesn't rely\non native addons. This condition can be disabled via the\n--no-addons
flag.\"node\"
- matches for any Node.js environment. Can be a CommonJS or ES\nmodule file. In most cases explicitly calling out the Node.js platform is\nnot necessary.\"import\"
- matches when the package is loaded via import
or\nimport()
, or via any top-level import or resolve operation by the\nECMAScript module loader. Applies regardless of the module format of the\ntarget file. Always mutually exclusive with \"require\"
.\"require\"
- matches when the package is loaded via require()
. The\nreferenced file should be loadable with require()
although the condition\nmatches regardless of the module format of the target file. Expected\nformats include CommonJS, JSON, and native addons but not ES modules as\nrequire()
doesn't support them. Always mutually exclusive with\n\"import\"
.\"default\"
- the generic fallback that always matches. Can be a CommonJS\nor ES module file. This condition should always come last.Within the \"exports\"
object, key order is significant. During condition\nmatching, earlier entries have higher priority and take precedence over later\nentries. The general rule is that conditions should be from most specific to\nleast specific in object order.
Using the \"import\"
and \"require\"
conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.
The \"node-addons\"
condition can be used to provide an entry point which\nuses native C++ addons. However, this condition can be disabled via the\n--no-addons
flag. When using \"node-addons\"
, it's recommended to treat\n\"default\"
as an enhancement that provides a more universal entry point, e.g.\nusing WebAssembly instead of a native addon.
Conditional exports can also be extended to exports subpaths, for example:
\n{\n \"exports\": {\n \".\": \"./index.js\",\n \"./feature.js\": {\n \"node\": \"./feature-node.js\",\n \"default\": \"./feature.js\"\n }\n }\n}\n
\nDefines a package where require('pkg/feature.js')
and\nimport 'pkg/feature.js'
could provide different implementations between\nNode.js and other JS environments.
When using environment branches, always include a \"default\"
condition where\npossible. Providing a \"default\"
condition ensures that any unknown JS\nenvironments are able to use this universal implementation, which helps avoid\nthese JS environments from having to pretend to be existing environments in\norder to support packages with conditional exports. For this reason, using\n\"node\"
and \"default\"
condition branches is usually preferable to using\n\"node\"
and \"browser\"
condition branches.
In addition to direct mappings, Node.js also supports nested condition objects.
\nFor example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:
\n{\n \"exports\": {\n \"node\": {\n \"import\": \"./feature-node.mjs\",\n \"require\": \"./feature-node.cjs\"\n },\n \"default\": \"./feature.mjs\"\n }\n}\n
\nConditions continue to be matched in order as with flat conditions. If\na nested condition does not have any mapping it will continue checking\nthe remaining conditions of the parent condition. In this way nested\nconditions behave analogously to nested JavaScript if
statements.
When running Node.js, custom user conditions can be added with the\n--conditions
flag:
node --conditions=development index.js\n
\nwhich would then resolve the \"development\"
condition in package imports and\nexports, while resolving the existing \"node\"
, \"node-addons\"
, \"default\"
,\n\"import\"
, and \"require\"
conditions as appropriate.
Any number of custom conditions can be set with repeat flags.
", "type": "module", "displayName": "Resolving user conditions" }, { "textRaw": "Community Conditions Definitions", "name": "community_conditions_definitions", "desc": "Condition strings other than the \"import\"
, \"require\"
, \"node\"
,\n\"node-addons\"
and \"default\"
conditions\nimplemented in Node.js core are ignored by default.
Other platforms may implement other conditions and user conditions can be\nenabled in Node.js via the --conditions
/ -C
flag.
Since custom package conditions require clear definitions to ensure correct\nusage, a list of common known package conditions and their strict definitions\nis provided below to assist with ecosystem coordination.
\n\"types\"
- can be used by typing systems to resolve the typing file for\nthe given export. This condition should always be included first.\"browser\"
- any web browser environment.\"development\"
- can be used to define a development-only environment\nentry point, for example to provide additional debugging context such as\nbetter error messages when running in a development mode. Must always be\nmutually exclusive with \"production\"
.\"production\"
- can be used to define a production environment entry\npoint. Must always be mutually exclusive with \"development\"
.For other runtimes, platform-specific condition key definitions are maintained\nby the WinterCG in the Runtime Keys proposal specification.
\nNew conditions definitions may be added to this list by creating a pull request\nto the Node.js documentation for this section. The requirements for listing\na new condition definition here are that:
\n\"types\"
condition is a good example: It\ndoesn't really belong in the Runtime Keys proposal but is a good fit\nhere in the Node.js docs.The above definitions may be moved to a dedicated conditions registry in due\ncourse.
", "type": "module", "displayName": "Community Conditions Definitions" }, { "textRaw": "Self-referencing a package using its name", "name": "self-referencing_a_package_using_its_name", "meta": { "added": [ "v13.1.0", "v12.16.0" ], "changes": [ { "version": [ "v13.6.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31002", "description": "Unflag self-referencing a package using its name." } ] }, "desc": "Within a package, the values defined in the package's\npackage.json
\"exports\"
field can be referenced via the package's name.\nFor example, assuming the package.json
is:
// package.json\n{\n \"name\": \"a-package\",\n \"exports\": {\n \".\": \"./index.mjs\",\n \"./foo.js\": \"./foo.js\"\n }\n}\n
\nThen any module in that package can reference an export in the package itself:
\n// ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./index.mjs.\n
\nSelf-referencing is available only if package.json
has \"exports\"
, and\nwill allow importing only what that \"exports\"
(in the package.json
)\nallows. So the code below, given the previous package, will generate a runtime\nerror:
// ./another-module.mjs\n\n// Imports \"another\" from ./m.mjs. Fails because\n// the \"package.json\" \"exports\" field\n// does not provide an export named \"./m.mjs\".\nimport { another } from 'a-package/m.mjs';\n
\nSelf-referencing is also available when using require
, both in an ES module,\nand in a CommonJS one. For example, this code will also work:
// ./a-module.js\nconst { something } = require('a-package/foo.js'); // Loads from ./foo.js.\n
\nFinally, self-referencing also works with scoped packages. For example, this\ncode will also work:
\n// package.json\n{\n \"name\": \"@my/package\",\n \"exports\": \"./index.js\"\n}\n
\n// ./index.js\nmodule.exports = 42;\n
\n// ./other.js\nconsole.log(require('@my/package'));\n
\n$ node other.js\n42\n
",
"type": "module",
"displayName": "Self-referencing a package using its name"
}
],
"type": "misc",
"displayName": "Package entry points"
},
{
"textRaw": "Dual CommonJS/ES module packages",
"name": "dual_commonjs/es_module_packages",
"desc": "Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json
\"main\"
specifying the\nCommonJS entry point and package.json
\"module\"
specifying the ES module\nentry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level \"module\"
field.
Node.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n'pkg'
and 'pkg/es-module'
, or both at the same specifier via Conditional\nexports). Unlike in the scenario where \"module\"
is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.
When an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the pkgInstance
created by\nconst pkgInstance = require('pkg')
is not the same as the pkgInstance
\ncreated by import pkgInstance from 'pkg'
(or an alternative main path like\n'pkg/module'
). This is the “dual package hazard,” where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.
If the package main export is a constructor, an instanceof
comparison of\ninstances created by the two versions returns false
, and if the export is an\nobject, properties added to one (like pkgInstance.foo = 3
) are not present on\nthe other. This differs from how import
and require
statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like Babel or esm
.
First, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage might instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package might contain\nare intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since import
can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.
A package might also switch from CommonJS to ES module syntax in a breaking\nchange version bump. This has the disadvantage that the\nnewest version of the package would only be usable in ES module-supporting\nversions of Node.js.
\nEvery pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:
\nrequire
and import
.'pkg'
can be used by both require
to\nresolve to a CommonJS file and by import
to resolve to an ES module file.\n(And likewise for exported paths, e.g. 'pkg/feature'
.)import { name } from 'pkg'
rather\nthan import pkg from 'pkg'; pkg.name
.Write the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\nConditional exports, the ES module wrapper is used for import
and the\nCommonJS entry point for require
.
// ./node_modules/pkg/package.json\n{\n \"type\": \"module\",\n \"exports\": {\n \"import\": \"./wrapper.mjs\",\n \"require\": \"./index.cjs\"\n }\n}\n
\nThe preceding example uses explicit extensions .mjs
and .cjs
.\nIf your files use the .js
extension, \"type\": \"module\"
will cause such files\nto be treated as ES modules, just as \"type\": \"commonjs\"
would cause them\nto be treated as CommonJS.\nSee Enabling.
// ./node_modules/pkg/index.cjs\nexports.name = 'value';\n
\n// ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n
\nIn this example, the name
from import { name } from 'pkg'
is the same\nsingleton as the name
from const { name } = require('pkg')
. Therefore ===
\nreturns true
when comparing the two name
s and the divergent specifier hazard\nis avoided.
If the module is not simply a list of named exports, but rather contains a\nunique function or object export like module.exports = function () { ... }
,\nor if support in the wrapper for the import pkg from 'pkg'
pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:
import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
\nThis approach is appropriate for any of the following use cases:
\nutilities
\npackage is used directly in an application, and a utilities-plus
package\nadds a few more functions to utilities
. Because the wrapper exports\nunderlying CommonJS files, it doesn't matter if utilities-plus
is written in\nCommonJS or ES module syntax; it will work either way.A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. \"./module\"
, to point to an all-ES module-syntax\nversion of the package. This could be used via import 'pkg/module'
by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn't affect the ES module version (for example, because the package is\nstateless):
// ./node_modules/pkg/package.json\n{\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./index.cjs\",\n \"./module\": \"./wrapper.mjs\"\n }\n}\n
",
"type": "module",
"displayName": "Approach #1: Use an ES module wrapper"
},
{
"textRaw": "Approach #2: Isolate state",
"name": "approach_#2:_isolate_state",
"desc": "A package.json
file can define the separate CommonJS and ES module entry\npoints directly:
// ./node_modules/pkg/package.json\n{\n \"type\": \"module\",\n \"exports\": {\n \"import\": \"./index.mjs\",\n \"require\": \"./index.cjs\"\n }\n}\n
\nThis can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package's management of state is carefully isolated (or the package is\nstateless).
\nThe reason that state is an issue is because both the CommonJS and ES module\nversions of the package might get used within an application; for example, the\nuser's application code could import
the ES module version while a dependency\nrequire
s the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.
Aside from writing a stateless package (if JavaScript's Math
were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it's shared between the potentially loaded\nCommonJS and ES module instances of the package:
If possible, contain all state within an instantiated object. JavaScript's\nDate
, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:
import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
\nThe new
keyword isn't required; a package's function can return a new\nobject, or modify a passed-in object, to keep the state external to the\npackage.
Isolate the state in one or more CommonJS files that are shared between the\nCommonJS and ES module versions of the package. For example, if the CommonJS\nand ES module entry points are index.cjs
and index.mjs
, respectively:
// ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n
\n// ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n state,\n};\n
\nEven if pkg
is used via both require
and import
in an application (for\nexample, via import
in application code and via require
by a dependency)\neach reference of pkg
will contain the same state; and modifying that\nstate from either module system will apply to both.
Any plugins that attach to the package's singleton would need to separately\nattach to both the CommonJS and ES module singletons.
\nThis approach is appropriate for any of the following use cases:
\nEven with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.
\nAs with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n\"./module\"
, to point to an all-ES module-syntax version of the package:
// ./node_modules/pkg/package.json\n{\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./index.cjs\",\n \"./module\": \"./index.mjs\"\n }\n}\n
",
"type": "module",
"displayName": "Approach #2: Isolate state"
}
],
"type": "module",
"displayName": "Writing dual packages while avoiding or minimizing hazards"
}
],
"type": "misc",
"displayName": "Dual CommonJS/ES module packages"
},
{
"textRaw": "Node.js `package.json` field definitions",
"name": "node.js_`package.json`_field_definitions",
"desc": "This section describes the fields used by the Node.js runtime. Other tools (such\nas npm) use\nadditional fields which are ignored by Node.js and not documented here.
\nThe following fields in package.json
files are used in Node.js:
\"name\"
- Relevant when using named imports within a package. Also used\nby package managers as the name of the package.\"main\"
- The default module when loading the package, if exports is not\nspecified, and in versions of Node.js prior to the introduction of exports.\"packageManager\"
- The package manager recommended when contributing to\nthe package. Leveraged by the Corepack shims.\"type\"
- The package type determining whether to load .js
files as\nCommonJS or ES modules.\"exports\"
- Package exports and conditional exports. When present,\nlimits which submodules can be loaded from within the package.\"imports\"
- Package imports, for use by modules within the package\nitself.{\n \"name\": \"package-name\"\n}\n
\nThe \"name\"
field defines your package's name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.
The \"name\"
field can be used in addition to the \"exports\"
field to\nself-reference a package using its name.
{\n \"main\": \"./index.js\"\n}\n
\nThe \"main\"
field defines the entry point of a package when imported by name\nvia a node_modules
lookup. Its value is a path.
When a package has an \"exports\"
field, this will take precedence over the\n\"main\"
field when importing the package by name.
It also defines the script that is used when the package directory is loaded\nvia require()
.
// This resolves to ./path/to/directory/index.js.\nrequire('./path/to/directory');\n
",
"type": "module",
"displayName": "`\"main\"`"
},
{
"textRaw": "`\"packageManager\"`",
"name": "`\"packagemanager\"`",
"meta": {
"added": [
"v16.9.0",
"v14.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "{\n \"packageManager\": \"<package manager name>@<version>\"\n}\n
\nThe \"packageManager\"
field defines which package manager is expected to be\nused when working on the current project. It can be set to any of the\nsupported package managers, and will ensure that your teams use the exact\nsame package manager versions without having to install anything else other than\nNode.js.
This field is currently experimental and needs to be opted-in; check the\nCorepack page for details about the procedure.
", "type": "module", "displayName": "`\"packageManager\"`" }, { "textRaw": "`\"type\"`", "name": "`\"type\"`", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": [ "v13.2.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Unflag `--experimental-modules`." } ] }, "desc": "The \"type\"
field defines the module format that Node.js uses for all\n.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\npackage.json
file contains a top-level field \"type\"
with a value of\n\"module\"
.
The nearest parent package.json
is defined as the first package.json
found\nwhen searching in the current folder, that folder's parent, and so on up\nuntil a node_modules folder or the volume root is reached.
// package.json\n{\n \"type\": \"module\"\n}\n
\n# In same folder as preceding package.json\nnode my-app.js # Runs as ES module\n
\nIf the nearest parent package.json
lacks a \"type\"
field, or contains\n\"type\": \"commonjs\"
, .js
files are treated as CommonJS. If the volume\nroot is reached and no package.json
is found, .js
files are treated as\nCommonJS.
import
statements of .js
files are treated as ES modules if the nearest\nparent package.json
contains \"type\": \"module\"
.
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
\nRegardless of the value of the \"type\"
field, .mjs
files are always treated\nas ES modules and .cjs
files are always treated as CommonJS.
{\n \"exports\": \"./index.js\"\n}\n
\nThe \"exports\"
field allows defining the entry points of a package when\nimported by name loaded either via a node_modules
lookup or a\nself-reference to its own name. It is supported in Node.js 12+ as an\nalternative to the \"main\"
that can support defining subpath exports\nand conditional exports while encapsulating internal unexported modules.
Conditional Exports can also be used within \"exports\"
to define different\npackage entry points per environment, including whether the package is\nreferenced via require
or via import
.
All paths defined in the \"exports\"
must be relative file URLs starting with\n./
.
// package.json\n{\n \"imports\": {\n \"#dep\": {\n \"node\": \"dep-node-native\",\n \"default\": \"./dep-polyfill.js\"\n }\n },\n \"dependencies\": {\n \"dep-node-native\": \"^1.0.0\"\n }\n}\n
\nEntries in the imports field must be strings starting with #
.
Package imports permit mapping to external packages.
\nThis field defines subpath imports for the current package.
", "type": "module", "displayName": "`\"imports\"`" } ], "type": "misc", "displayName": "Node.js `package.json` field definitions" } ] } ] }