Skip to content

Instantly share code, notes, and snippets.

@coltenkrauter
Last active August 20, 2025 18:30
Show Gist options
  • Save coltenkrauter/ecd779402963faa4e9b1a7b09fd5c6f2 to your computer and use it in GitHub Desktop.
Save coltenkrauter/ecd779402963faa4e9b1a7b09fd5c6f2 to your computer and use it in GitHub Desktop.
TypeScript NPM Package Best Practices (Browser-first; TS+JS; ESM+CJS)

TypeScript NPM Package Best Practices Checklist

(Browser-first; works in TS & JS; supports ESM + CJS)


1. Types

2. Dual Module Formats

  • Build both ESM and CJS.
  • Use Node conditional exports in package.json: { "exports": { ".": { "import": "./esm/index.js", "require": "./cjs/index.js" } } }
  • Keep "main" pointing to CJS for legacy tools.

3. Package.json Hygiene

  • If ESM-first: set "type": "module".
  • Restrict publish using "files" or .npmignore.
  • Ensure "exports", "main", "types" are correct.

4. Build System

  • Automate dual builds using:
    • tsup (esbuild-based, fast)
    • Rollup (mature bundler for libs)
  • Generate source maps.
  • Ship unminified builds; let consumers optimize.

5. Consumer-Friendly TS

  • Avoid forcing esModuleInterop or path aliases downstream.
  • Stick to standard import/export.

6. Output Targets

  • Compile to ES2018+ (or lowest you need).
  • Include source maps for debug.

7. Runtime Compatibility

  • Browser: avoid Node APIs unless polyfilled.
  • Node ESM: no __dirname/__filename. Use import.meta.url.

8. Tree-Shaking

  • Use named exports only.
  • Add "sideEffects": false if safe. Ref: webpack docs.

9. Dependencies

10. Testing & Release

  • Test packaged build in:
    • TS project (import + type checks)
    • JS project (require + bundler import)
  • CI matrix: Node + browser/bundler.

Node.js Notes

  • Always ship CJS alongside ESM → works with require() + import.
  • Dual package is future-proof; see Node ESM & CJS guide.
  • For Node-only libs: ESM-only possible, but document and consider fallback.
  • Replace __dirname with import.meta equivalents in ESM.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment