How-to › Ship an SDK

How to ship a dual-format TypeScript SDK without duplicate types#

Serve ESM and CommonJS from one npm package built twice with TypeScript, with one error class and one declaration of it, checked by publint and are-the-types-wrong.

Audience
Library maintainer
Level
advanced
Topic
Design SDK ergonomics per language
Languages
TypeScript
Verified

Your SDK ships an ESM build and a CommonJS build. An app imports it, and one of the app’s dependencies requires it, so both builds load in one process. The ApiError that dependency throws fails err instanceof ApiError in the app, and tsc refuses to assign one build’s ApiError to the other’s with an error about #private.

What you get

You will end up with one package whose exports map serves both formats, with one runtime copy of the error class and one declaration of it. A test loads the tarball both ways. This is for you if callers catch your SDK’s errors by class.

Short answer

Build the SDK twice with tsc, once as CommonJS and once as ESM, and map each build in the package’s exports map with its own types condition. Move the error class and any other state into one module that only the CommonJS build emits, and import it by the package’s own name from both builds. Check the tarball with publint and are-the-types-wrong, then load it with import and require in one process.

You will need

A TypeScript SDK that builds with tsc, and Node 22. tsup 9.0.0 declares ^22.18.0 || ^24.11.0 || >=26.0.0 in engines, so on Node 22.12.0 npm ci prints an EBADENGINE warning and installs it, and with --engine-strict it stops. The sample needs no network: each build runs in a temporary directory, and an in-memory fetch stands in for the API. Node keeps its account of the dual package hazard in a separate repository.1

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
hand-written exports map with two tsc buildsYou want plain tsc output and full control of which file each condition loadsTwo tsconfig files, a build order, and a nested package.json your build script has to writeSeveral entry points, where a tool that writes the exports map saves the bookkeeping
publint and arethetypeswrongBefore every publish, whichever row builds the packageTwo development dependencies and a packed tarball per check; neither tool looks for a duplicated classNever skip them; pair them with a test that loads both formats
tshyYou want the exports map written for you from a list of source entry pointsIt owns exports in package.json, and its polyfill hides the shared class behind a @ts-ignore importYou want every import in the source checked by tsc
tsupA package already built with tsup, where a second config entry costs less than a migrationAn esbuild and rollup toolchain from a project its README calls no longer actively maintainedYou are choosing a build tool, or you want plain tsc output

Two tsc runs cost the most configuration and lock you into nothing beyond TypeScript itself. tshy writes the map for you, and its README treats the hazard as a fact of life rather than something the tool fixes. tsup reaches the same result as the hand-written row with a second config entry. Its README at 9.0.0 opens with a warning, “This project is not actively maintained anymore,” and asks readers to consider tsdown, which this page did not run.

Write the exports map by hand

Give each condition its own types and default, and add an export entry for the module that both builds share. The "./errors" entry has no import or require branch, so both formats resolve to the same CommonJS file.

  "exports": {
    ".": {
      "import": {
        "types": "./build/esm/index.d.ts",
        "default": "./build/esm/index.js"
      },
      "require": {
        "types": "./build/cjs/index.d.ts",
        "default": "./build/cjs/index.js"
      }
    },
    "./errors": {
      "types": "./build/cjs/errors.d.ts",
      "default": "./build/cjs/errors.js"
    }

The CommonJS build sets module to commonjs. The ESM build keeps nodenext from the base config and leaves src/errors.ts out, so it never emits a second copy of the class.

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "build/esm"
  },
  "exclude": ["src/errors.ts"]
}

The source imports the error class by the package’s own name, which Node and TypeScript both resolve through the exports map.

import { ApiError } from 'widgets-sdk/errors'
import type { ClientOptions, Widget } from './types.js'

export { ApiError } from 'widgets-sdk/errors'
export type { ClientOptions, FetchLike, ResponseLike, Widget } from './types.js'

Widget and the option types are type-only exports. They leave nothing in the JavaScript, so two module instances have nothing to disagree about, and every export you can make type-only is one the hazard cannot reach.

Build in order and mark the CommonJS folder

The ESM build reads build/cjs/errors.d.ts, so the CommonJS build runs first. A nested package.json tells Node that the .js files under build/cjs are CommonJS, inside a package whose top-level type is module.

rmSync('build', { recursive: true, force: true })
// CommonJS first: the ESM build reads build/cjs/errors.d.ts.
run('tsconfig.cjs.json')
writeFileSync('build/cjs/package.json', '{ "type": "commonjs" }\n')
run('tsconfig.esm.json')

Check it worked

Run the check from the sample directory. It builds the SDK, packs it, lints the tarball, asks are-the-types-wrong which declaration file each resolution mode reaches, and installs the tarball into the two consumer projects.

node check.mjs
two tsc runs, CommonJS first
  build/cjs: errors.d.ts errors.js index.d.ts index.js package.json types.d.ts types.js
  build/esm: index.d.ts index.js types.d.ts types.js

publint 0.3.25: 0 messages
attw 0.18.5 --profile node16: exit 0, 0 problems
  ignored by the profile, node10: NoResolution on ., NoResolution on ./errors
  widgets-sdk         node16 from CJS  build/cjs/index.d.ts   CJS
  widgets-sdk         node16 from ESM  build/esm/index.d.ts   ESM
  widgets-sdk         bundler          build/esm/index.d.ts
  widgets-sdk/errors  node16 from CJS  build/cjs/errors.d.ts  CJS
  widgets-sdk/errors  node16 from ESM  build/cjs/errors.d.ts  CJS
  widgets-sdk/errors  bundler          build/cjs/errors.d.ts

esm-app  import       {"id":"w_1","name":"sprocket"}
esm-app  error thrown by the require() copy: instanceof ApiError true, status 404, request id req_42
cjs-app  require()    {"id":"w_1","name":"sprocket"}
cjs-app  error thrown by the import copy:    instanceof ApiError true, status 404, request id req_42
tsc esm-app/check.mts: exit 0
tsc cjs-app/check.cts: exit 0

Both apps print instanceof ApiError true for an error thrown through the other format, and both check files type-check. Each one assigns the other format’s ApiError to its own. The test file asserts the same results, then breaks the package three ways and the build order once, and expects each check to catch it. The fifth test covers the tshy polyfill.

node --test dual.test.mjs
1..5
# tests 5
# suites 0
# pass 5
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 16119.692068

Build the same source with tsup and tshy

The comparison builds eight variants of one source and loads each tarball both ways. “One class” means both apps printed true; “one type” means both check files compiled.

node compare.mjs tsc
build                                    attw             one class  one type
two tsc runs, every module in both       pass             false      false
two tsc runs, errors in one CJS module   pass             true       true
two tsc runs, one types entry for both   fail FalseESM    true       true
node compare.mjs tsup
build                                    attw             one class  one type
tsup, one config                         pass             false      false
tsup, errors as a CJS-only entry         pass             true       true
node compare.mjs tshy
build                                    attw             one class  one type
tshy, defaults                           pass             false      false
tshy, polyfill typed from errors-cjs     pass             true       false
tshy, polyfill re-exporting the CJS file pass             true       true

Every default build passes are-the-types-wrong with two classes inside, so a green attw says nothing about the hazard. tsup closes it with a second config entry that builds the class as CommonJS only and an external entry for widgets-sdk/errors.

export default [
  // The error class, built once, as CommonJS only.
  { entry: ['src/errors.ts'], format: ['cjs'], dts: true, outDir: 'build' },
  // Everything else, in both formats, importing that one file by package name.
  { entry: ['src/index.ts'], format: ['esm', 'cjs'], dts: true, outDir: 'build', external: ['widgets-sdk/errors'] },
]

tshy’s README describes a dialect polyfill for module local state: a -cjs.cts file holds the value, and the ESM file loads the CommonJS build’s copy. Typed by importing errors-cjs.cjs, the polyfill fixes the runtime check and fails the type check: tsc follows that import and emits errors-cjs.d.cts into the ESM folder, a second declaration. Re-exporting the CommonJS build’s file passes both, because the emitted errors.d.ts then points at the CommonJS declaration.

// The ESM build's errors.js re-exports the CommonJS build's class, so the
// emitted errors.d.ts points at the CommonJS declaration file as well.
// @ts-ignore the CommonJS build sits beside this one once tshy has run
export { ApiError } from '../commonjs/errors.js'

The @ts-ignore is the cost: inside the ESM build, ApiError is typed any, so only the CommonJS build checks how the source uses it.

When it goes wrong

The error crosses formats and instanceof is false. Every module went into both builds, so the package holds two classes, and TypeScript sees two declarations that a #private field keeps apart.2

node pitfall.mjs
esm-app  import       {"id":"w_1","name":"sprocket"}
esm-app  error thrown by the require() copy: instanceof ApiError false, status 404, request id req_42
tsc esm-app/check.mts: exit 2
check.mts(5,14): error TS2322: Type 'import("<consumers>/node_modules/widgets-sdk/build/cjs/errors").ApiError' is not assignable to type 'import("<consumers>/node_modules/widgets-sdk/build/esm/errors", { with: { "resolution-mode": "import" } }).ApiError'.
  Property '#private' in type 'ApiError' refers to a different member that cannot be accessed from within type 'ApiError'.

Move the class into the shared module, as the exports map in the first step does.

The ESM build fails with TS2307: Cannot find module 'widgets-sdk/errors'. It ran before the CommonJS build had written errors.d.ts, so run the CommonJS build first. The fourth test asserts that failure.

are-the-types-wrong reports FalseESM, which its documentation titles Masquerading as ESM. One types entry serves both conditions, so a CommonJS caller type-checks against ESM declarations. Give require its own types file.

When not to do this

Do not ship two formats if your callers run Node 22.12 or later. That release lets require load an ES module without a flag, and one ESM build has one class by construction.

Do not move a stateless SDK into a shared module. A package with no classes that callers match and no module-level state gains nothing from the extra export entry, and it pays for a build order.

Do not adopt the self-name import if callers still type-check with node10 resolution. The earlier check shows that mode resolving neither entry point, because it ignores the exports map.

A green are-the-types-wrong run proves nothing about the hazard, because every default build in the comparison passed it with two classes inside. Keep the test that loads the tarball both ways.

Last verified

Verified 2026-11-30 against Node 22.23.5, TypeScript 6.0.3, publint 0.3.25, @arethetypeswrong/cli 0.18.5, tshy 4.1.4, and tsup 9.0.0. Every output block is what the command preceding it printed. Each of the four rows ran here, and the page takes no tool’s behavior from its documentation alone.

Footnotes

  1. The section on dual packages used to sit in Node’s own packages documentation. It moved to the package-examples repository, which opens it with a notice: the text is copied as-is, and much of it has been outdated since Node started to support require(esm). The notice asks readers not to follow it when they start a package, for the time being. The two approaches it describes, an ES module wrapper and isolated state, follow the notice unchanged. ↩︎ Back to text

  2. A declaration file does not describe a class’s private fields, so the emitted .d.ts keeps the single line #private; in their place. The handbook’s section on private members then decides the matter: a private member in the target type must have originated from the same class. Two identical files are two origins, which is all the error on this page says. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.