arethetypeswrong / arethetypeswrong.github.io

Tool for analyzing TypeScript types of npm packages
https://arethetypeswrong.github.io
MIT License
1.12k stars 38 forks source link

Seeking NodeJS + TypeScript Demo Project with CJS and ESM Exports #169

Closed UrielCh closed 2 months ago

UrielCh commented 4 months ago

Hi,

Does anyone have a demo NodeJS + TypeScript project that serves as a best practice example for exporting with both CJS and ESM formats?

I've been unable to find a clear way to build a project that supports both pure CJS and pure ESM exports.

I believe there should be three types of project templates:

Is it possible for a clean project to maintain a single set of typings? It seems like ESM and CJS might each require their own set of typings.

Thank you!

andrewbranch commented 4 months ago

ESM and CJS do necessarily require their own set of typings. I suggest looking at https://github.com/isaacs/tshy as a tool to generate both formats. However, I also suggest considering shipping ESM only as a best practice.

atomicpages commented 2 months ago

What @andrewbranch said. There's also https://tsup.egoist.dev/ for bundling ESM and CJS formats. You can do this pretty easily with their config:

import { defineConfig } from "tsup";

export default defineConfig({
  entry: ["src/index.ts"],
  splitting: false,
  format: ["esm", "cjs"],
  sourcemap: true,
  clean: true,
  dts: true,
});

If you don't want yet another tool then use this as a guide:

File Ext Package Type
CJS .js, .d.ts CommonJS
ESM .mjs, .d.mts CommonJS
CJS .js, .d.ts module
ESM .cjs, .d.cts module