# 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.

Source: https://voxgig.com/howto/typescript-sdk-esm-and-commonjs-without-duplicate-types

- Audience: library-maintainer
- Level: advanced
- Languages: typescript
- Verified: 2026-11-30
- Published: 2026-11-30

## 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](https://github.com/nodejs/package-examples/blob/main/guide/07-dual-packages/README.md)
in a separate repository.[^1]

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [hand-written exports map with two `tsc` builds](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports) | You want plain `tsc` output and full control of which file each condition loads | Two tsconfig files, a build order, and a nested `package.json` your build script has to write | Several entry points, where a tool that writes the exports map saves the bookkeeping |
| [publint](https://publint.dev/docs/javascript-api) and [arethetypeswrong](https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/packages/cli/README.md) | Before every publish, whichever row builds the package | Two development dependencies and a packed tarball per check; neither tool looks for a duplicated class | Never skip them; pair them with a test that loads both formats |
| [tshy](https://github.com/isaacs/tshy#dual-package-hazards) | You want the exports map written for you from a list of source entry points | It owns `exports` in `package.json`, and its polyfill hides the shared class behind a `@ts-ignore` import | You want every import in the source checked by `tsc` |
| [tsup](https://tsup.egoist.dev/#generate-declaration-file) | A package already built with tsup, where a second config entry costs less than a migration | An esbuild and rollup toolchain from a project its README calls no longer actively maintained | You 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](https://github.com/egoist/tsup/blob/v9.0.0/README.md) 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.

```json title="sdk/package.json"
  "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.

```json title="sdk/tsconfig.esm.json"
{
  "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.

```ts title="sdk/src/index.ts"
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`.

```js title="sdk/build.mjs"
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.

```bash
node check.mjs
```

```text output
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.

```bash
node --test dual.test.mjs
```

```text output
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.

```bash
node compare.mjs tsc
```

```text output
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
```

```bash
node compare.mjs tsup
```

```text output
build                                    attw             one class  one type
tsup, one config                         pass             false      false
tsup, errors as a CJS-only entry         pass             true       true
```

```bash
node compare.mjs tshy
```

```text output
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`](https://tsup.egoist.dev/#excluding-packages) entry for `widgets-sdk/errors`.

```js title="variants/tsup-errors-entry/tsup.config.js"
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](https://github.com/isaacs/tshy#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.

```ts title="variants/tshy-polyfill-reexport/src/errors.ts"
// 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]

```bash
node pitfall.mjs
```

```text output
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](https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/docs/problems/FalseESM.md).
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](https://nodejs.org/docs/latest-v22.x/api/modules.html#loading-ecmascript-modules-using-require)
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.

## Related how-tos

- [Package one utility for Node, Deno, Bun, and browsers](/howto/package-a-utility-for-node-deno-and-browsers)

- [Expose typed SDK errors callers match without parsing text](/howto/typed-sdk-errors-callers-can-match)

- [Choose a release automation tool for an SDK repository](/howto/choose-a-release-automation-tool-for-an-sdk)

- [Unwrap response envelopes and keep headers and request IDs](/howto/unwrap-response-envelopes-without-losing-headers)

## 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.

[^1]: The section on dual packages used to sit in Node's own `packages` documentation. It moved to
the [package-examples repository](https://github.com/nodejs/package-examples/blob/main/guide/07-dual-packages/README.md),
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.

[^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](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#private-and-protected-members-in-classes)
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.