{ "type": "module", "source": "doc/api/packages.md", "meta": { "changes": [ { "version": [ "v14.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34117", "description": "Add package `\"imports\"` field." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Unflag conditional exports." }, { "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", "type": "misc", "meta": { "changes": [ { "version": [ "v14.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34117", "description": "Add package `\"imports\"` field." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Unflag conditional exports." }, { "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.

\n

This page provides guidance for package authors writing package.json files\nalong with a reference for the package.json fields defined by Node.js.

", "type": "misc", "displayName": "Introduction" }, { "textRaw": "Determining module system", "name": "determining_module_system", "desc": "

Node.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements within ES module code:

\n\n

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 within ES module code:

\n\n

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.

", "modules": [ { "textRaw": "`package.json` and file extensions", "name": "`package.json`_and_file_extensions", "desc": "

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.

\n

A package.json \"type\" value of \"module\" tells Node.js to interpret .js\nfiles within that package as using ES module syntax.

\n

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.

\n
// 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
\n

Files ending with .mjs are always loaded as ES modules regardless of\nthe nearest parent package.json.

\n

Files ending with .cjs are always loaded as CommonJS regardless of the\nnearest parent package.json.

\n
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
\n

The .mjs and .cjs extensions can be used to mix types within the same\npackage:

\n", "type": "module", "displayName": "`package.json` and file extensions" }, { "textRaw": "`--input-type` flag", "name": "`--input-type`_flag", "desc": "

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.

\n
node --input-type=module --eval \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | node --input-type=module\n
\n

For completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.

", "type": "module", "displayName": "`--input-type` flag" } ], "type": "misc", "displayName": "Determining module system" }, { "textRaw": "Package entry points", "name": "package_entry_points", "desc": "

In a package’s package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". The \"main\" field is supported\nin all versions of Node.js, but its capabilities are limited: it only defines\nthe main entry point of the package.

\n

The \"exports\" field provides an alternative to \"main\" where the\npackage main entry point can be defined while also encapsulating the package,\npreventing any other entry points besides those defined in \"exports\".\nThis encapsulation allows module authors to define a public interface for\ntheir package.

\n

If both \"exports\" and \"main\" are defined, the \"exports\" field\ntakes precedence over \"main\". \"exports\" are not specific to ES\nmodules or CommonJS; \"main\" is overridden by \"exports\" if it\nexists. As such \"main\" cannot be used as a fallback for CommonJS but it\ncan be used as a fallback for legacy versions of Node.js that do not support the\n\"exports\" field.

\n

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.

\n

Warning: Introducing the \"exports\" field prevents consumers of a\npackage 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.

\n

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 previous exported main, lib,\nfeature, and the package.json could use the following package.exports:

\n
{\n  \"name\": \"my-mod\",\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.js\": \"./feature/index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

Alternatively a project could choose to export entire folders:

\n
{\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/*\": \"./lib/*.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/*\": \"./feature/*.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package \"./*\": \"./*\". This exposes every file\nin the package at the cost of disabling the encapsulation and potential tooling\nbenefits this provides. As the ES Module loader in Node.js enforces the use of\nthe full specifier path, exporting the root rather than being explicit\nabout entry is less expressive than either of the prior examples. Not only\nis encapsulation lost but module consumers are unable to\nimport feature from 'my-mod/feature' as they need to provide the full\npath import feature from 'my-mod/feature/index.js.

", "modules": [ { "textRaw": "Main entry point export", "name": "main_entry_point_export", "desc": "

To set the main entry point for a package, it is advisable to define both\n\"exports\" and \"main\" in the package’s package.json file:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": \"./main.js\"\n}\n
\n

When 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.

\n

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.

", "type": "module", "displayName": "Main entry point export" }, { "textRaw": "Subpath exports", "name": "subpath_exports", "stability": 1, "stabilityText": "Experimental", "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
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
\n

Now only the defined subpath in \"exports\" can be imported by a consumer:

\n
import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\n

While other subpaths will error:

\n
import submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n
", "type": "module", "displayName": "Subpath exports" }, { "textRaw": "Subpath imports", "name": "subpath_imports", "stability": 1, "stabilityText": "Experimental", "desc": "

In addition to the \"exports\" field, it is possible to define internal\npackage import maps that only apply to import specifiers from within the package\nitself.

\n

Entries in the imports field must always start with # to ensure they are\ndisambiguated from package specifiers.

\n

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
\n

where 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.

\n

Unlike the \"exports\" field, the \"imports\" field permits mapping to external\npackages.

\n

The resolution rules for the imports field are otherwise\nanalogous to the exports field.

", "type": "module", "displayName": "Subpath imports" }, { "textRaw": "Subpath patterns", "name": "subpath_patterns", "stability": 1, "stabilityText": "Experimental", "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.

\n

For these use cases, subpath export patterns can be used instead:

\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/*\": \"./src/features/*.js\"\n  },\n  \"imports\": {\n    \"#internal/*\": \"./src/internal/*.js\"\n  }\n}\n
\n

The left hand matching pattern must always end in *. All instances of * on\nthe right hand side will then be replaced with this value, including if it\ncontains any / separators.

\n
import featureX from 'es-module-package/features/x';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z';\n// Loads ./node_modules/es-module-package/src/internal/z.js\n
\n

This is a direct static replacement without any special handling for file\nextensions. In the previous example, pkg/features/x.json would be resolved to\n./src/features/x.json.js in the mapping.

\n

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.

", "type": "module", "displayName": "Subpath patterns" }, { "textRaw": "Exports sugar", "name": "exports_sugar", "stability": 1, "stabilityText": "Experimental", "desc": "

If the \".\" export is the only export, the \"exports\" field provides sugar\nfor this case being the direct \"exports\" field value.

\n

If the \".\" export has a fallback array or string value, then the\n\"exports\" field can be set to this value directly.

\n
{\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
\n

can be written:

\n
{\n  \"exports\": \"./main.js\"\n}\n
", "type": "module", "displayName": "Exports sugar" }, { "textRaw": "Conditional exports", "name": "conditional_exports", "stability": 1, "stabilityText": "Experimental", "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.

\n

For example, a package that wants to provide different ES module exports for\nrequire() and import can be written:

\n
// package.json\n{\n  \"main\": \"./main-require.cjs\",\n  \"exports\": {\n    \"import\": \"./main-module.js\",\n    \"require\": \"./main-require.cjs\"\n  },\n  \"type\": \"module\"\n}\n
\n

Node.js supports the following conditions out of the box:

\n\n

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.

\n

Other conditions such as \"browser\", \"electron\", \"deno\", \"react-native\",\netc., are unknown to Node.js, and thus ignored. Runtimes or tools other than\nNode.js can use them at their discretion. Further restrictions, definitions, or\nguidance on condition names might occur in the future.

\n

Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.

\n

Conditional exports can also be extended to exports subpaths, for example:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./feature\": {\n      \"node\": \"./feature-node.js\",\n      \"default\": \"./feature.js\"\n    }\n  }\n}\n
\n

Defines a package where require('pkg/feature') and import 'pkg/feature'\ncould provide different implementations between Node.js and other JS\nenvironments.

\n

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.

", "type": "module", "displayName": "Conditional exports" }, { "textRaw": "Nested conditions", "name": "nested_conditions", "stability": 1, "stabilityText": "Experimental", "desc": "

In addition to direct mappings, Node.js also supports nested condition objects.

\n

For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \"node\": {\n      \"import\": \"./feature-node.mjs\",\n      \"require\": \"./feature-node.cjs\"\n    },\n    \"default\": \"./feature.mjs\",\n  }\n}\n
\n

Conditions continue to be matched in order as with flat conditions. If\na nested conditional 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.

", "type": "module", "displayName": "Nested conditions" }, { "textRaw": "Resolving user conditions", "name": "resolving_user_conditions", "desc": "

When running Node.js, custom user conditions can be added with the\n--conditions flag:

\n
node --conditions=development main.js\n
\n

which would then resolve the \"development\" condition in package imports and\nexports, while resolving the existing \"node\", \"default\", \"import\", and\n\"require\" conditions as appropriate.

\n

Any number of custom conditions can be set with repeat flags.

", "type": "module", "displayName": "Resolving user conditions" }, { "textRaw": "Self-referencing a package using its name", "name": "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:

\n
// package.json\n{\n  \"name\": \"a-package\",\n  \"exports\": {\n    \".\": \"./main.mjs\",\n    \"./foo\": \"./foo.js\"\n  }\n}\n
\n

Then 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 ./main.mjs.\n
\n

Self-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:

\n
// ./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
\n

Self-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:

\n
// ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\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.

\n

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.

", "modules": [ { "textRaw": "Dual package hazard", "name": "dual_package_hazard", "desc": "

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.

\n

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.

", "type": "module", "displayName": "Dual package hazard" }, { "textRaw": "Writing dual packages while avoiding or minimizing hazards", "name": "writing_dual_packages_while_avoiding_or_minimizing_hazards", "desc": "

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.

\n

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.

\n

Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:

\n
    \n
  1. The package is usable via both require and import.
  2. \n
  3. The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.
  4. \n
  5. The package main entry point, e.g. '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'.)
  6. \n
  7. The package provides named exports, e.g. import { name } from 'pkg' rather\nthan import pkg from 'pkg'; pkg.name.
  8. \n
  9. The package is potentially usable in other ES module environments such as\nbrowsers.
  10. \n
  11. The hazards described in the previous section are avoided or minimized.
  12. \n
", "modules": [ { "textRaw": "Approach #1: Use an ES module wrapper", "name": "approach_#1:_use_an_es_module_wrapper", "desc": "

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.

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
\n

The 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.

\n
// ./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
\n

In 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 names and the divergent specifier hazard\nis avoided.

\n

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:

\n
import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
\n

This approach is appropriate for any of the following use cases:

\n\n

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):

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\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:

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
\n

This 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).

\n

The 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\nrequires 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.

\n

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:

\n
    \n
  1. \n

    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:

    \n
    import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
    \n

    The 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.

    \n
  2. \n
  3. \n

    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:

    \n
    // ./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
    \n

    Even 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.

    \n
  4. \n
\n

Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.

\n

This approach is appropriate for any of the following use cases:

\n\n

Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.

\n

As 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:

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\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.

\n

The following fields in package.json files are used in Node.js:

\n", "modules": [ { "textRaw": "`\"name\"`", "name": "`\"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": "Remove the `--experimental-resolve-self` option." } ] }, "desc": "\n
{\n  \"name\": \"package-name\"\n}\n
\n

The \"name\" field defines your package’s name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.

\n

The \"name\" field can be used in addition to the \"exports\" field to\nself-reference a package using its name.

", "type": "module", "displayName": "`\"name\"`" }, { "textRaw": "`\"main\"`", "name": "`\"main\"`", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "\n
{\n  \"main\": \"./main.js\"\n}\n
\n

The \"main\" field defines the script that is used when the package directory\nis loaded via require(). Its value\nis a path.

\n
require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.\n
\n

When a package has an \"exports\" field, this will take precedence over the\n\"main\" field when importing the package by name.

", "type": "module", "displayName": "`\"main\"`" }, { "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`." } ] }, "stability": 1, "stabilityText": "Experimental", "desc": "\n

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.

\n

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\".

\n

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.

\n
// 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
\n

If 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.

\n

import statements of .js files are treated as ES modules if the nearest\nparent package.json contains \"type\": \"module\".

\n
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
\n

Regardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.

", "type": "module", "displayName": "`\"type\"`" }, { "textRaw": "`\"exports\"`", "name": "`\"exports\"`", "meta": { "added": [ "v12.7.0" ], "changes": [ { "version": [ "v14.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31008", "description": "Implement logical conditional exports ordering." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Remove the `--experimental-conditional-exports` option." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29978", "description": "Implement conditional exports." } ] }, "stability": 1, "stabilityText": "Experimental", "desc": "\n
{\n  \"exports\": \"./index.js\"\n}\n
\n

The \"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.

\n

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.

\n

All paths defined in the \"exports\" must be relative file URLs starting with\n./.

", "type": "module", "displayName": "`\"exports\"`" }, { "textRaw": "`\"imports\"`", "name": "`\"imports\"`", "meta": { "added": [ "v14.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "\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
\n

Entries in the imports field must be strings starting with #.

\n

Import maps permit mapping to external packages.

\n

This field defines subpath imports for the current package.

", "type": "module", "displayName": "`\"imports\"`" } ], "type": "misc", "displayName": "Node.js `package.json` field definitions" } ] } ] }