Publishing useComments hook to NPM
This lesson will teach you how to publish a React hook as an NPM library.
In the previous modules, we added a commenting system to a sample blog application. But what if we want to add comments to multiple applications? We could need to copy-paste the hook to different projects. However, we can also publish the hook as an NPM library and import it into any project. That is what we'll do in this lesson, and it's going to take just a few steps!
To deploy our hook as an NPM package, we need to use a bundler.
We're going to use Microbundle, which is a zero-configuration bundler for tiny modules. It comes with TypeScript support out of the box, and it's pretty straightforward to set up.
We can install it with the following command:
Before we use it, let's fill a few things in the
"name": "@anemone/newline-use-comments"— the package name. I'm prefixing it with my NPM username
"source": "lib/useComments.ts"— the source code.
"main": "dist/index.js"— the location where Microbundle should generate the CommonJS bundle.
"types": "dist/useComments.d.ts"— TypeScript types location. Microbundle will generate types from our module and put them there.
"module": "dist/index.esm.js"— the location where theESM bundle should be placed
"files": [ "dist" ]— files that should be included in the package. We want to ignore all the blog application code.
"version": "0.0.1"— the version of our package. Feel free to set a different number.
"private": false— otherwise we won't be able to publish the library.
Since we're publishing the package from the same place where we have the blog application, we will add a separate tsconfig specifically for the library.
Then, we will add a new script to the
package.json that will compile the
source code to the
Now, we can try and run it with the following command: