The letter S in a light blue, stylized speech bubble followed by SpeakBits
SpeakBitsThe letter S in a light blue, stylized speech bubble followed by SpeakBits
Trending
Top
New
Controversial
Search
Groups

Enjoying SpeakBits?

Support the development of it by donating to Patreon or Ko-Fi.
About
Rules
Terms
Privacy
EULA
Cookies
Blog
Have feedback? We'd love to hear it!

Create npm package with CommonJS and ESM support in TypeScript

mastykarz.nl
submitted
a year ago
bythrowschentoprogramming

Summary

CommonJS and ESM are not compatible with each other. To produce both, your package needs to contain two versions of the code. To support usage in TypeScript, you’ll also need to include type definitions. The following sections describe how to set up the project to produce such output.

Node.js uses the.mjs extension to distinguish between CJS and ESM code. You need to rename the.js and.mj files to make it easier to build the package in both formats. You can also use the exports property to specify how the package should be loaded.

When building the ESM package, the helper script updates the extension to.mjs. This is required for the E SM build to work correctly. To support CJS and ESM, you need to produce two versions of the code, one for each module system.

 web site website internet site site screen CRT screen monitor oscilloscope scope cathode-ray oscilloscope CRO-0
14

3 Comments

3
joesch
a year ago
Really nice post! I wish I had this three years ago even setting up a component library for my organization
2
justadev
a year ago
I hate how adding an ESM package breaks everything
2
throwschenOP
a year ago
Big reason this article walks through having both!