package
.../package/main.js
The exports
field in the package.json
of a package allows to declare which module should be used when using module requests like import "package"
or import "package/sub/path"
. It replaces the default implementation that returns main
field resp. index.js
files for "package"
and the file system lookup for "package/sub/path"
.
When the exports
field is specified, only these module requests are available. Any other requests will lead to a ModuleNotFound Error.
In general the exports
field should contain an object where each properties specifies a sub path of the module request. For the examples above the following properties could be used: "."
for import "package"
and "./sub/path"
for import "package/sub/path"
. Properties ending with a /
will forward a request with this prefix to the old file system lookup algorithm.
An example:
{
"exports": {
".": "./main.js",
"./sub/path": "./secondary.js",
"./prefix/": "./directory/",
"./prefix/deep/": "./other-directory/"
}
}
Module request | Result |
---|---|
Module request Result
| .../package/main.js |
Module request Result
| .../package/secondary.js |
Module request Result
| .../package/directory/some/file.js |
Module request Result
| .../package/other-directory/file.js |
Module request Result
Error | Error |
Instead of providing a single result, the package author may provide a list of results. In such a scenario this list is tried in order and the first valid result will be used.
Note: Only the first valid result will be used, not all valid results.
Example:
{
"exports": {
"./things/": ["./good-things/", "./bad-things/"]
}
}
Here package/things/apple
might be found in .../package/good-things/apple
or in .../package/bad-things/apple
.
Instead of providing results directly in the exports
field, the package author may let the module system choose one based on conditions about the environment.
In this case an object mapping conditions to results should be used. Conditions are tried in object order. Conditions that contain invalid results are skipped. Conditions might be nested to create a logical AND. The last condition in the object might be the special "default"
condition, which is always matched.
Example:
{
"exports": {
".": {
"red": "./stop.js",
"yellow": "./stop.js",
"green": {
"free": "./drive.js",
"default": "./wait.js"
},
"default": "./drive-carefully.js"
}
}
}
This translates to something like:
if (red && valid('./stop.js')) return './stop.js';
if (yellow && valid('./stop.js')) return './stop.js';
if (green) {
if (free && valid('./drive.js')) return './drive.js';
if (valid('./wait.js')) return './wait.js';
}
if (valid('./drive-carefully.js')) return './drive-carefully.js';
throw new ModuleNotFoundError();
The available conditions vary depending on the module system and tool used.
When only a single entry ("."
) into the package should be supported the { ".": ... }
object nesting can be omitted:
{
"exports": "./index.mjs"
}
{
"exports": {
"red": "./stop.js",
"green": "./drive.js"
}
}
In an object where each key is a condition, order of properties is significant. Conditions are handled in the order they are specified.
Example: { "red": "./stop.js", "green": "./drive.js" }
!= { "green": "./drive.js", "red": "./stop.js" }
(when both red
and green
conditions are set, first property will be used)
In an object where each key is a subpath, order of properties (subpaths) is not significant. More specific paths are preferred over less specific ones.
Example: { "./a/": "./x/", "./a/b/": "./y/", "./a/b/c": "./z" }
== { "./a/b/c": "./z", "./a/b/": "./y/", "./a/": "./x/" }
(order will always be: ./a/b/c
> ./a/b/
> ./a/
)
exports
field is preferred over other package entry fields like main
, module
, browser
or custom ones.
One of these conditions is set depending on the syntax used to reference the module:
Condition | Description | Supported by |
---|---|---|
Condition Description Supported by
Request is issued from ESM syntax or similar. | Request is issued from ESM syntax or similar. | webpack, Node.js |
Condition Description Supported by
Request is issued from CommonJs/AMD syntax or similar. | Request is issued from CommonJs/AMD syntax or similar. | webpack, Node.js |
Condition Description Supported by
Request is issued from a stylesheet reference. | Request is issued from a stylesheet reference. | |
Condition Description Supported by
Request is issued from a sass stylesheet reference. | Request is issued from a sass stylesheet reference. | |
Condition Description Supported by
Request is issued from a asset reference. | Request is issued from a asset reference. | |
Condition Description Supported by
Request is issued from a normal script tag without module system. | Request is issued from a normal script tag without module system. |
These conditions might also be set additionally:
Condition | Description | Supported by |
---|---|---|
Condition Description Supported by
All module syntax that allows to reference javascript supports ESM. | All module syntax that allows to reference javascript supports ESM. (only combined with import or require ) | webpack |
Condition Description Supported by
Request is issued from typescript that is interested in type declarations. | Request is issued from typescript that is interested in type declarations. |
import
The following syntax will set the import
condition:
import
declarations in ESMimport()
expression<script type="module">
in HTML<link rel="preload/prefetch">
in HTMLnew Worker(..., { type: "module" })
import
sectionimport.hot.accept/decline([...])
Worklet.addModule
require
The following syntax will set the require
condition:
require(...)
define()
require([...])
require.resolve()
require.ensure([...])
require.context
module.hot.accept/decline([...])
<script src="...">
style
The following syntax will set the style
condition:
@import
<link rel="stylesheet">
asset
The following syntax will set the asset
condition:
url()
new URL(..., import.meta.url)
<img src="...">
script
The following syntax will set the script
condition:
<script src="...">
script
should only be set when no module system is supported. When the script is preprocessed by a system supporting CommonJs it should set require
instead.
This condition should be used when looking for a javascript file that can be injected as script tag in a HTML page without additional preprocessing.
The following conditions are set for various optimizations:
Condition | Description | Supported by |
---|---|---|
Condition Description Supported by
In a production environment. | In a production environment. No devtooling should be included. | webpack |
Condition Description Supported by
In a development environment. | In a development environment. Devtooling should be included. | webpack |
Note: Since production
and development
is not supported by everyone, no assumption should be made when none of these is set.
The following conditions are set depending on the target environment:
Condition | Description | Supported by |
---|---|---|
Condition Description Supported by
Code will run in a browser. | Code will run in a browser. | webpack |
Condition Description Supported by
Code will run in electron. | Code will run in electron. | webpack |
Condition Description Supported by
Code will run in a (Web)Worker. | Code will run in a (Web)Worker. | webpack |
Condition Description Supported by
Code will run in a Worklet. | Code will run in a Worklet. | |
Condition Description Supported by
Code will run in Node.js. | Code will run in Node.js. | webpack, Node.js |
Condition Description Supported by
Code will run in Deno. | Code will run in Deno. | |
Condition Description Supported by
Code will run in react-native. | Code will run in react-native. |
Note: electron
, worker
and worklet
comes combined with either node
or browser
, depending on the context.
Since there are multiple versions of each environment the following guidelines apply:
node
: See engines
field for compatibility.browser
: Compatible with current Spec and stage 4 proposals at time of publishing the package. Polyfilling resp. transpiling must be handled on consumer side. deno
: TBDreact-native
: TBDThe following conditions are set depending on which tool preprocesses the source code.
Condition | Description | Supported by |
---|---|---|
Condition Description Supported by
Processed by webpack. | Processed by webpack. | webpack |
Sadly there is no node-js
condition for Node.js as runtime. This would simplify creating exceptions for Node.js.
The following tools support custom conditions:
Tool | Supported | Notes |
---|---|---|
Tool Supported Notes Node.js no | no | |
Tool Supported Notes webpack yes | yes | Use resolve.conditionNames configuration option. |
For custom conditions the following naming schema is recommended:
<company-name>:<condition-name>
Examples: example-corp:beta
, google:internal
, `
All patterns are explained with a single "."
entry into the package, but they can be extended from multiple entries too, by repeating the pattern for each entry.
These pattern should be used as guide not as strict ruleset. They can be adapted to the individual packages.
These pattern are based on the following list of goals/assumptions:
exports
should be written to use fallbacks for unknown future cases. default
condition can be used for that.Depending on the package intention maybe something else makes sense and in this case the patterns should be adopted to that. Example: For a command line tool a browser-like future and fallback doesn't make a lot of sense, and in this case node.js-like environments and fallbacks should be used instead.
For complex use cases multiple patterns need to be combined by nesting these conditions.
These patterns make sense for packages that do not use environment specific APIs.
{
"type": "module",
"exports": "./index.js"
}
Note: Providing only a ESM comes with restrictions for node.js. Such a package would only work in Node.js >= 14 and only when using import
. It won't work with require()
.
{
"type": "module",
"exports": {
"node": {
"module": "./index.js",
"require": "./index.cjs"
},
"default": "./index.js"
}
}
Most tools get the ESM version. Node.js is an exception here. It gets a CommonJs version when using require()
. This will lead to two instances of these package when referencing it with require()
and import
, but that doesn't hurt as the package doesn't have state.
The module
condition is used as optimization when preprocessing node-targeted code with a tool that supports ESM for require()
(like a bundler, when bundling for Node.js). For such a tool the exception is skipped. This is technically optional, but bundlers would include the package source code twice otherwise.
You can also use the stateless pattern if you are able to isolate your package state in JSON files. JSON is consumable from CommonJs and ESM without polluting the graph with the other module system.
Note that here stateless also means class instances are not tested with instanceof
as there can be two different classes because of the double module instantiation.
{
"type": "module",
"exports": {
"node": {
"module": "./index.js",
"import": "./wrapper.js",
"require": "./index.cjs"
},
"default": "./index.js"
}
}
// wrapper.js
import cjs from './index.cjs';
export const A = cjs.A;
export const B = cjs.B;
In a stateful package we must ensure that the package is never instantiated twice.
This isn't a problem for most tools, but Node.js is again an exception here. For Node.js we always use the CommonJs version and expose named exports in the ESM with a ESM wrapper.
We use the module
condition as optimization again.
{
"type": "commonjs",
"exports": "./index.js"
}
Providing "type": "commonjs"
helps to statically detect CommonJs files.
{
"type": "module",
"exports": {
"script": "./dist-bundle.js",
"default": "./index.js"
}
}
Note that despite using "type": "module"
and .js
for dist-bundle.js
this file is not in ESM format. It should use globals to allow direct consumption as script tag.
These patterns make sense when a package contains two versions, one for development and one for production. E. g. the development version could include additional code for better error message or additional warnings.
{
"type": "module",
"exports": {
"development": "./index-with-devtools.js",
"default": "./index-optimized.js"
}
}
When the development
condition is supported we use the version enhanced for development. Otherwise, in production or when mode is unknown, we use the optimized version.
{
"type": "module",
"exports": {
"development": "./index-with-devtools.js",
"production": "./index-optimized.js",
"node": "./wrapper-process-env.cjs",
"default": "./index-optimized.js"
}
}
// wrapper-process-env.cjs
if (process.env.NODE_ENV !== 'development') {
module.exports = require('./index-optimized.cjs');
} else {
module.exports = require('./index-with-devtools.cjs');
}
We prefer static detection of production/development mode via the production
or development
condition.
Node.js allows to detection production/development mode at runtime via process.env.NODE_ENV
, so we use that as fallback in Node.js. Sync conditional importing ESM is not possible and we don't want to load the package twice, so we have to use CommonJs for the runtime detection.
When it's not possible to detect mode we fallback to the production version.
A fallback environment should be chosen that makes sense for the package to support future environments. In general a browser-like environment should be assumed.
{
"type": "module",
"exports": {
"node": "./index-node.js",
"worker": "./index-worker.js",
"default": "./index.js"
}
}
{
"type": "module",
"exports": {
"electron": {
"node": "./index-electron-node.js",
"default": "./index-electron.js"
},
"node": "./index-node.js",
"default": "./index.js"
}
}
This is an example for a package that has optimizations for production and development usage with runtime detection for process.env
and also ships a CommonJs and ESM version
{
"type": "module",
"exports": {
"node": {
"development": {
"module": "./index-with-devtools.js",
"import": "./wrapper-with-devtools.js",
"require": "./index-with-devtools.cjs"
},
"production": {
"module": "./index-optimized.js",
"import": "./wrapper-optimized.js",
"require": "./index-optimized.cjs"
},
"default": "./wrapper-process-env.cjs"
},
"development": "./index-with-devtools.js",
"production": "./index-optimized.js",
"default": "./index-optimized.js"
}
}
This is an example for a package that supports Node.js, browser and electron, has optimizations for production and development usage with runtime detection for process.env
and also ships a CommonJs and ESM version.
{
"type": "module",
"exports": {
"electron": {
"node": {
"development": {
"module": "./index-electron-node-with-devtools.js",
"import": "./wrapper-electron-node-with-devtools.js",
"require": "./index-electron-node-with-devtools.cjs"
},
"production": {
"module": "./index-electron-node-optimized.js",
"import": "./wrapper-electron-node-optimized.js",
"require": "./index-electron-node-optimized.cjs"
},
"default": "./wrapper-electron-node-process-env.cjs"
},
"development": "./index-electron-with-devtools.js",
"production": "./index-electron-optimized.js",
"default": "./index-electron-optimized.js"
},
"node": {
"development": {
"module": "./index-node-with-devtools.js",
"import": "./wrapper-node-with-devtools.js",
"require": "./index-node-with-devtools.cjs"
},
"production": {
"module": "./index-node-optimized.js",
"import": "./wrapper-node-optimized.js",
"require": "./index-node-optimized.cjs"
},
"default": "./wrapper-node-process-env.cjs"
},
"development": "./index-with-devtools.js",
"production": "./index-optimized.js",
"default": "./index-optimized.js"
}
}
Looks complex, yes. We were already able to reduce some complexity due to a assumption we can make: Only node
need a CommonJs version and can detect production/development with process.env
.
default
export. It's handled differently between tooling. Only use named exports..cjs
or type: "commonjs"
in package.json to clearly mark source code as CommonJs. This makes it statically detectable for tools if CommonJs or ESM is used. This is important for tools that only support ESM and no CommonJs.data:
url requests are supported.