Deploying a react package to NPM

Olushola Benedict
2 min readFeb 24, 2022

Deploying a react (or any JavaScript) package to npm is fairly easy, the differences between the two pertinent JavaScript module systems, ESM(ECMAScript Modules) and Cjs(CommonJs) can make it a bit tricky.

As it is evident, with Cjs, you cannot easily require ESM majorly because of the top level await implementation of ESM, in the context of ESM though, a Cjs module can be imported with minimal hastles.

If the package to be published is written in ESM and it’s to be used within the context of an ESM project then there is nothing to worry about. We run into issues when our published ESM package is being required in Cjs.

To circumvent this, we can write our package in ESM and use a bundler to transpile it to Cjs with optional named exports. This way, we get the best of both worlds and make our package safe to be used with any of the two module systems. I will be illustrating the process with rollup bundler.

Let’s say we want to publish the below module exported with ESM;

src/index.tsx

We need to configure rollup to work with our project, below is a rollup config with a plugin (rollup-plugin-typescript2) that bundles typescript files.

rollup.config.js

With these configurations in place, we can run the command rollup -c to bundle the package. The dist folder will be created with the file index.js containing the cjs transpile of our package.

The compiled file looks like this.

dist/index.js

I have put together a repo here to get you started quickly. Thanks for reading.

--

--