Skip to content
jshacks.dev
Packages

Ship ESM and CommonJS with conditional exports

Publish one package that works with import and require by mapping each condition to its own file in exports, and avoid loading both copies at once.

1 min read
Summarize in AI

Some of your users run require(), and others use import. Map each condition to its own build in exports, and give each build its own types file.

package.jsonJSON
{
  "name": "my-lib",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "import": {
        "types": "./dist/index.d.ts",
        "default": "./dist/index.js"
      },
      "require": {
        "types": "./dist/index.d.cts",
        "default": "./dist/index.cjs"
      }
    }
  }
}

With "type": "module", .js files are ESM and .cjs files are CommonJS, so no further flag is needed. Either style gets the same answer:

Shell
node -e "console.log(require('my-lib').add(1, 2))"
node --input-type=module -e "import { add } from 'my-lib'; console.log(add(1, 2))"
Text
3
3

Node.js picks the import or require condition from how the consumer loaded the package, as described in conditional exports. The hazard is state: an app that loads both builds holds two copies of any singleton, so keep shared state in a third module or avoid it.

Share

More snippets

Packages

Initialize a package with npm init

Initialize a package.json with npm init, skip the questions with the yes flag, and set your own defaults for author and license in npm config.

1 min read
Packages

Generate a changelog from commits

Turn conventional commit messages into a CHANGELOG.md section with conventional-changelog, grouped by feature and fix. Works with any Git history.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.