It's 2023, and if you want to write a library in the npm ecosystem with good CommonJS (CJS) and ECMAScript Module (ESM) support, here are some things to consider:
- First, you can use tools like tsup or any other tool you prefer to compile your source code into these two formats. You can also choose any other formats like UMD or IIFE as well.
- If your package provides multiple entry points, you'll need to configure your package.json accordingly. This may involve setting properties like
exports. You can refer to the official Node.js documentation on package entry points. Additionally, you can use tools like publint and arethetypeswrong to perform checks. There's even a community-created CLI available for arethetypeswrong.
- Your users may encounter TypeScript errors when using your library because TypeScript Compiler only started providing ESM support starting from version 4.7. They need to set
- What if your users have a lower TypeScript version or don't know how to configure it? You can learn from the approach taken by Next.js. Create a bunch of files like
entry1.d.tsin the root directory and have them point to your compiled artifacts.