This video is available to students only

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!

Bundling#

To deploy our hook as an NPM package, we need to use a bundler.

A module bundler is a tool that bundles JavaScript or TypeScript modules into a single JavaScript file that can be executed in the browser.

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 package.json:

  • "name": "@anemone/newline-use-comments" — the package name. I'm prefixing it with my NPM username @anemone.

  • "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 dist/ directory.

Now, we can try and run it with the following command:

Start a new discussion. All notification go to the author.