Skip to content
Back to blog
Engineering6 minute read

Shipping Dual ESM & CJS TypeScript Packages Without Breaking Consumers

A practical playbook for package.json exports maps, declaration resolution, and CI smoke tests that keep Node, Vite, and Bun happy.

ASRaka Mahendra
  • Engineering
  • TypeScript
  • Packaging
  • ESM
Cover art for “Shipping Dual ESM & CJS TypeScript Packages Without Breaking Consumers”

Publishing a TypeScript library that behaves cleanly across legacy Node.js CommonJS projects, modern ESM runtimes, and strict bundler setups is still one of the sharpest paper cuts in the ecosystem. Most failures happen silently inside the exports field of package.json.

1. Order your conditional exports explicitly

TypeScript resolves the types condition first inside each branch. When you ship both .mjs and .cjs bundles, pair them with distinct .d.mts and .d.cts declarations so NodeNext never flags a dual-package hazard.

{
  "exports": {
    ".": {
      "import": {
        "types": "./dist/index.d.mts",
        "default": "./dist/index.mjs"
      },
      "require": {
        "types": "./dist/index.d.cts",
        "default": "./dist/index.cjs"
      }
    }
  }
}

2. Run a real consumer smoke test in CI

Unit tests running inside Vitest or ts-node rarely catch packaging bugs because they resolve source files directly. Add a lightweight script that invokes both dynamic import() and createRequire() against your compiled dist folder before every release.

  • Validate packed tarballs with npm pack –dry-run to prevent leaking fixtures.
  • Keep sideEffects: false explicit so downstream bundlers can tree-shake unused helpers.
  • Avoid mixing default and named exports in CommonJS entrypoints.

3. Verify tree-shaking and side effects

Bundlers like Vite, esbuild, and Webpack rely on static ESM structure and clean sideEffects metadata to drop unused code. Even a single top-level helper that mutates a global registry can force consumers to ship your entire library.

Inspect your compiled output with an explicit bundle-size check in pull requests so accidental dependency creep is caught before tagging a release.

4. Pre-publish release checklist

Before running npm publish, verify that declaration files resolve cleanly under both moduleResolution: bundler and moduleResolution: nodenext. Automating this matrix once pays dividends on every minor release.

Copied