Skip to content

Instantly share code, notes, and snippets.

@sokra
Last active October 6, 2023 08:36
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sokra/e032a0f17c1721c71cfced6f14516c62 to your computer and use it in GitHub Desktop.
Save sokra/e032a0f17c1721c71cfced6f14516c62 to your computer and use it in GitHub Desktop.

exports field (webpack guideline)

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 request will lead to a ModuleNotFound Error.

General syntax

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
package .../package/main.js
package/sub/path .../package/secondary.js
package/prefix/some/file.js .../package/directory/some/file.js
package/prefix/deep/file.js .../package/other-directory/file.js
package/main.js Error

Alternatives

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.

Conditional syntax

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.

Abbreviation

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"
	}
}

Notes about ordering

In an object where each key in an condition, order of properties is significant. Conditions are handled in the order they are specified.

In an object where each key is a subpath, order of properties is not significant. More specific properties are preferred over less specific ones.

exports field is preferred over other package entry fields like main, module, browser or custom ones.

Conditions

Reference syntax

One of these conditions is set depending on the syntax used to reference the module:

Condition Description Supported by
import Request is issued from ESM syntax or similar. webpack, Node.js
require Request is issued from CommonJs/AMD syntax or similar. webpack, Node.js
style Request is issued from a stylesheet reference.
sass Request is issued from a sass stylesheet reference.
asset Request is issued from a asset reference.
script Request is issued from a normal script tag without module system.

These conditions might also be set additionally:

Condition Description Supported by
module All module syntax that allows to reference javascript supports ESM.
(only combined with import or require)
webpack
types Request is issued from typescript that is interested in type declarations.

import

The following syntax will set the import condition:

  • ESM import declarations in ESM
  • JS import() expression
  • HTML <script type="module"> in HTML
  • HTML <link rel="preload/prefetch"> in HTML
  • JS new Worker(..., { type: "module" })
  • WASM import section
  • ESM HMR (webpack) import.hot.accept/decline([...])
  • JS Worklet.addModule
  • Using javascript as entrypoint

require

The following syntax will set the require condition:

  • CommonJs require(...)
  • AMD define()
  • AMD require([...])
  • CommonJs require.resolve()
  • CommonJs (webpack) require.ensure([...])
  • CommonJs (webpack) require.context
  • CommonJs HMR (webpack) module.hot.accept/decline([...])
  • HTML <script src="...">

style

The following syntax will set the style condition:

  • CSS @import
  • HTML <link rel="stylesheet">

asset

The following syntax will set the asset condition:

  • CSS url()
  • ESM new URL(..., import.meta.url)
  • HTML <img src="...">

script

The following syntax will set the script condition:

  • HTML <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.

Optimizations

The following conditions are set for various optimizations:

Condition Description Supported by
production In a production environment.
No devtooling should be included.
webpack
development 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.

Target environment

The following conditions are set depending on the target environment:

Condition Description Supported by
browser Code will run in a browser. webpack
electron Code will run in electron. webpack
worker Code will run in a (Web)Worker. webpack
worklet Code will run in a Worklet.
node Code will run in Node.js. webpack, Node.js
deno Code will run in Deno.
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.
    • Features that are not possible to polyfill or transpile should be used carefully as it limits the possible usage.
  • deno: TBD
  • react-native: TBD

Conditions: Preprocessor and runtimes

The following conditions are set depending on which tool preprocesses the source code.

Condition Description Supported 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.

Conditions: Custom

The following tools support custom conditions:

Tool Supported Notes
Node.js no
webpack 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, `

Common patterns

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:

  • Packages are rotting.
    • We assume at some point packages are no longer being maintained, but they are continued to be used.
    • exports should be written to use fallbacks for unknown future cases. default condition can be used for that.
    • As the future is unknown we assume an environment similar to browsers and module system similar to ESM.
  • Not all conditions are supported by every tool.
    • Fallbacks should be used to handled these cases.
    • We assume the following fallback make sense in general:
      • ESM > CommonJs
      • Production > Development
      • Browser > node.js

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.

Target environment independent packages

These patterns make sense for packages that do not use environment specific APIs.

Providing only an ESM version

{
	"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().

Providing CommonJs and ESM version (stateless)

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

Providing CommonJs and ESM version (stateful)

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

Providing only a CommonJs version

{
	"type": "commonjs",
	"exports": "./index.js"
}

Providing "type": "commonjs" helps to statically detect CommonJs files.

Providing a bundled script version for direct browser consumption

{
	"type": "module",
	"exports": {
		"script": "./dist-bundle.js",
		"default": "./index.js"
	}
}

Note that desprite 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.

Providing devtools or production optimizations

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.

Without Node.js runtime detection

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

With Node.js runtime detection

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

Providing different versions depending on target environment

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.

Providing Node.js, WebWorker and browser versions

{
	"type": "module",
	"exports": {
		"node": "./index-node.js",
		"worker": "./index-worker.js",
		"default": "./index.js"
	}
}

Providing Node.js, browser and electron versions

{
	"type": "module",
	"exports": {
		"electron": {
			"node": "./index-electron-node.js",
			"default": "./index-electron.js"
		},
		"node": "./index-node.js",
		"default": "./index.js"
	}
}

Combining patterns

Example 1

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"
	}
}

Example 2

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.

Guidelines

  • Avoid the default export. It's handled differently between tooling. Only use named exports.
  • Never provide different APIs or semantics for different conditions.
  • Write your source code as ESM and transpile to CJS via babel, typescript or similar tools.
  • Either use .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.
  • ESM used in packages support the following types of requests:
    • module requests are supported, pointing to other packages with a package.json.
    • relative requests are supported, pointing to other files within the package.
      • They must not point to files outside of the package.
    • data: url requests are supported.
    • other absolute or server-relative requests are not supported by default, but they might be supported by some tools or environments.
@Andarist
Copy link

{
	"exports": {
		".": "./main.js",
		"./sub/path": "./secondary.js",
		"./prefix/": "./directory/",
		"./prefix/deep/": "./other-directory/"
	}
}

Are you sure this is correct? It might be, but only the first condition is matched so I would expect a first matching "path" to be matched as well and if that's the case then "./prefix/deep/" wouldn't ever be matched because "./prefix/" would take precedence. Worth re-checking with node's algorithm, unless you are sure that this is OK.

"browser" condition

  1. I've found in the past many many people being confused about this one. Maybe changing its name here would be a good idea? A problem in the past was that people have expected it to be directly runnable in browsers whereas quite often this file has contained process.env.NODE_ENV references. This concern is alleviated by introducing support for "development" and "production" conditions but there is still one concern left - this file will contain module IDs when importing other non-relative modules, so it still won't be "directly runnable". At least until things like import maps get into browsers.
  2. Does it make sense for the file referenced by this condition to contain CJS? I would say no - CJS doesn't exist in browsers and won't in the future. Could this just be treated similarly to the proposed "module" condition?

The "electron" condition always occur together with either "browser" or "node". To allow it to work as expected, it must be specified before at least one of the companion conditions.

It's not clearly apparent what does it mean exactly and why this has to come before other conditions. I assume that when bundling for target: 'electron' other conditions might be matched and as the first one matched wins then we have a problem here. This is not obvious though - as a consumer I would be surprised by this.

@guybedford
Copy link

guybedford commented Jun 12, 2020

I cannot tell Webpack what to do so will not argue any unnecessary details further :) And for all that is written here, I only have one major disagreement really worth noting.

My major disagreement would actually be with the "default" field being sold as an anti-pattern and that throwing in new environments is favoured - this is actually actively hostile behaviour towards new JS platforms in future as it forces them to either be browsers (match the "browser" field) or to fail. This leads to situations similar to user agent faking where new environments need to "fake" existing ones to ensure they can grow their userbase.

For this reason I think it is actively very very dangerous to the ecosystem to discourage default over explicit checks, as it means whatever ecosystem we have in 10 years will be deeply scarred by compatibility faking.

@frank-dspeed
Copy link

frank-dspeed commented Jun 15, 2020

I can only say we should all take a step back and rethink about using package.json and module-resolve at all i researched now 5 years on that and can clear say those package identifiers are a hugh problem for the whole ECMAScript Ecosystem i started an effort to create rollup configs to hard fork cjs and bad esm packages that are using package identifiers and rewrite them to a clean esm bundle so that can be used in any project and later be transpiled by the bundling or packaging tool of the project that uses that dependency.

I think the best we all can do is go for ESM Only development and the user transpiles that when he uses it. So we would force the Ecosystem to publish ESM code only. And it would make clear that the nodejs require ecosystem is deprecated in Favor of the ECMAScript Module System.

It is not hard to rewrite CJS to ESM and most Packages already have ESM code so they only need to drop or separate the cjs code.

It can not be the solution to add 5 different versions in a single package and conditional expose them based on a none standard algo to resolve the dependencies. We need to understand that this adds unwanted complexity and leads to unexpected behavior. where a clean resolve path leads to clear results without unwanted behavior.

It can not be that i need to review a package.json and debug what i get from a dependency. a path can be easy rewritten the node resolve algo and webpack resolve algo needs studying it for some weeks to understand all side effects and differences in the tooling

@ctavan
Copy link

ctavan commented Jun 19, 2020

@frank-dspeed: The problem is not only ESM vs. CJS but rather about being able to pick different dependencies (e.g. Node.js crypto vs. Webcrypto vs. Polyfill for react-native) for different platforms. This would otherwise only be solved by publishing different packages for different platforms.

On the other hand I agree that this is becoming increasingly complex and more and more of a burden for package authors.

@developit
Copy link

@sokra - apologies for the late question here, but isn't "ES Current + Stage 4" going to be impossible to maintain at scale? Stage 4 can change quite quickly, certainly far quicker than developers would be updating their Babel+Webpack configurations.

Since the field is already called "browser", why not just make it synonymous with <script type=module>? That would be roughly ES2017, which is still pretty modern but not a moving target.

@sokra
Copy link
Author

sokra commented Jul 17, 2020

It's intentionally a moving target. It will never get out of date. Technically main is also a moving target as it orientates on the node.js versions and their JS versions.

Stage 4 can change quite quickly, certainly far quicker than developers would be updating their Babel+Webpack configurations.

packages can still not just randomly use new Ecma Features. This is still covered by SemVer and updating to a new EcmaScript code style is a breaking change and must happen in a major version.

I think it's acceptable that on major upgrades of dependencies you may have to upgrade webpack/babel config/presets too.

@developit
Copy link

@sokra if a package publishes once in april 2019 and then again in april 2020, would it be able to take advantage of the new ECMA features in its new release simply because time has passed? Or would you consider that a semver-breaking change?

My fear is that "main" is accepted by package authors as being a moving target for the node ecosystem, but because bundlers don't force users to transpile node_modules (yet?), "main" for web packages just represents the lowest-common denominator for that package's browser support. Anecdotally, there are a bunch of folks who have had to configure webpack to transpile specific npm modules within node_modules (idb, workbox-window, array-move, etc) as a result of this happening today. Maybe it would be possible to add a "browser-legacy" export key as a way to allow folks to ship ES5 without paying the transpiler overhead?

One other thought: it seems like the moving-target approach would be significantly more compelling (and less breaking) if Webpack was doing something to make that work for users, rather than relying on them to configure it as such. Have you considered providing a plugin that automates transpiling of node_modules based on the rules defined in this Gist? It would be super awesome to have a fast ECMA-to-ECMA transpiler that leverages Webpack's cache and transpiles based on how modules get resolved ("main" = skip, "exports" = node 13+, "browser" = escurrent).

@sokra
Copy link
Author

sokra commented Jul 17, 2020

@sokra if a package publishes once in april 2019 and then again in april 2020, would it be able to take advantage of the new ECMA features in its new release simply because time has passed? Or would you consider that a semver-breaking change?

I would consider this is breaking change. It's not yet defined but technically this should be handled by the engines field in package.json. You have an (implicit?) engines: { web: ">=es2019" } and updating it to engines: { web: ">=es2020" }. Even if it's (currently) implicit this is part of the contract of the package. This is very similar to main field + engines: { node: "..." }

@developit
Copy link

developit commented Jul 17, 2020

Would webpack be the thing analyzing engines.web? I haven't seen that proposed anywhere, seems like an important piece of the "browser" field as defined here.

I worry that it's misleading to use ECMA version names in a web context, since browser implementations are incomplete/mixed in a way that most developers can't be expected to keep track of. As an example: Edge 16 is an "ES2017" browser that supports destructured and default parameters, but it throws if the two are used in combination in an Arrow function. As a package author, can my "browser" entry with "engines.web":">=es2017" contain x=>({a=1})=>a, even though configurations are going to ship that to Edge 16 where it breaks? Or would an "es2017" target imply "ES2017 as implemented by browsers"? There are a bunch of these mismatches between spec and implementation, especially when you go newer than ES2017 - standard library changes, atomics, TCO, etc.

Some Google folks tried to propose a "yearly browser-implemented JS version" a while back, but it was rejected by standards folks since it required continual coordination between browsers.

@sokra
Copy link
Author

sokra commented Jul 18, 2020

Would webpack be the thing analyzing engines.web? I haven't seen that proposed anywhere, seems like an important piece of the "browser" field as defined here.

It's not anywhere proposed yet. I more used it as example of the implicit contract a package author creates. Even if it's not formalized in the package.json.

I also see the difficulties regarding formalizing it. If you would force me to come up with some spec for that I would use the ecmascript spec as factor and not the browsers. >=2018 would mean doesnt use anything from specs released after 2018. So now you only need polyfills/transpiliers that support es2018 features. Because many people also start with stage 4 feature early I would increase the minor version of a virtual version number everytime a proposal enters stage 4. >=2018.2 means all 2018 released features + the first 2 features that entered stage 4.

It's not perfect, but better than nothing.

"engines": {
  "ecma": ">=2018.2"
}

Otherwise we could also go a way where this is an implicit part of the package contract. We could add a note explaining this to this document.

@frank-dspeed
Copy link

i am for a dynamic webpack.config.js that establishes a own package discription formart and is able to reuse package.json filds if needed via json parse. this way it is abstracted from anything else

@Andarist
Copy link

Regarding "browser" condition:

Code will run in a browser.

What does it mean exactly? What about dependencies? Are those files still supposed to be processed by a tool like a bundler that is going to link dependencies somehow or are those ready-to-be-dropped as src of <script module/>? This is an important distinction and I've found many people to be confused by this because it has "always" been the first one (I'm talking about pkg.json#browser) but many people have expected to be the second one. I think it's a crucial piece of information in such an explainer like this that aims to document all of this craziness, once and for all.

@sokra
Copy link
Author

sokra commented Sep 26, 2020

This is orthogonal to the browser condition. Note that you can combine conditions, e. g. with conditions from https://gist.github.com/sokra/e032a0f17c1721c71cfced6f14516c62#reference-syntax
When only using the browser condition you can neither say it's processed by a bundler nor that it's dropped as script tag.
But you can't infer which cases a package supports from the exports field anyway. It's goal is only you help chosing the right entry when used in some specific way. It doesn't tell if a specific way of usage is supported.

@Andarist
Copy link

Ok, gotcha - makes sense although it's mind-boggling how this can nest. Will definitely have to hide the complexity of generating those maps in a tool. Thanks for the clarification.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment