Create and publish npm module library with esbuild typescript and react
Estimated reading time: 4 minutes
02/10/2022
Introduction
As an open source enthusiast, I like to share my code and give everyone the opportunity to use it. For that npm is my first choice. But there are some conditions to have a good library release on npm.
The first recommendation to follow is to support common js as Matteo Collina said :
For long time you needed to use js bundler like rollup, webpack and babel.
But that time is over because of a new generation of bundler. esbuild is one of them.
Today we will see how to create and publish a react library on npm with esbuild.
You can go to this repository for an example of this post.
Initialization
Create your folder project and initialize it.
Your package.json file should be defined :
Now we will install our dependencies.
Install dev dependencies
Don't forget to add react as a peer dependency if you are writing a react library with hooks or components.
Typescript config
Add tsconfig.json
file.
we don't need to build file with typescript because we will use esbuild for that. That's why
emitDeclarationOnly
is set to true
Write your module
Now you can write what you want. For example we will just write a function component to export.
Create src folder
then index.tsx
inside it.
Build your library
Now we need to build our package to CJS before publish it to npm.
Configure esbuild
Add esbuild :
Create an esbuild script for the bundle. Add a file esbuild.js
:
Add a build commande
And finally add a script in your package.json :
Now you can run :
Npm publish
Before publishing you need to be authenticated
Add these lines to your package.json :
Then publish it :
Congratulations, you have published your own library.
Publish package with Github action
Finally we just want to publish package when we trigger a github action. For that we have to add a file to .github/workflows/publish.yml
:
Add secret npm token
To run your action you need to add NPM_TOKEN environement variable.
Go to you npm account and generate an access token for CI :
Copy past this token in Github secret of your repository :
Now run your github action and take a coffe.
I'm Simon Boisset, freelance fullstack developer. I mainly work with React, React Native and Node.js. I'm available for development or consulting missions. Feel free to contact me on my website.