DEV Community

Cover image for How to Build and Publish Your First React NPM Package
Femi Akinyemi
Femi Akinyemi

Posted on • Edited on

How to Build and Publish Your First React NPM Package

Building and publishing your first Node Package Manager(NPM) is an exciting milestone in your journey as a developer. NPM has revolutionized how you share and reuse code in the JavaScript ecosystem, empowering developers to contribute to the open-source community and enhance the efficiency of their projects.

Whether you want to create a reusable library, a command-line tool, or any other piece of code that can be easily installed and integrated into projects, this article will guide you through the essential steps of building and publishing your first NPM package.

Prerequisites

To fully grasp the concepts presented in this tutorial, the following are required:

What is NPM

NPM is a powerful tool transforming how developers share and manage JavaScript code. It is the default package manager for Node.js, a popular runtime environment for executing JavaScript code outside a web browser. NPM is a vast repository of over a million packages, offering developers access to a wide range of open-source libraries, frameworks, and tools.

With NPM, developers can easily install, update, and manage dependencies for their projects, streamlining the development process and saving valuable time. Whether you need to integrate third-party libraries or share your code with the community, NPM provides a centralized platform for discovering, distributing, and collaborating on JavaScript packages.

What are you building

This article explains the process of building and publishing a React NPM package rather than creating an elaborate or complex package. Following the steps outlined in a simple example like the one you'll build, you'll develop a solid foundation to apply the same principles to more advanced packages.

In this article, you will build a package called capitalizefirstletterofastring. As the name suggests, this package capitalizes the first letter in a string. It is an excellent place to understand the essential steps in building and publishing an NPM package. So let's dive in and explore the process of creating and publishing your capitalizefirstletterofastring package.

Getting Started

To begin, you need to prepare your environment. A few ways to build a React package include tools like Bit, Storybook, Lerna, and TSDX. However, for this tutorial, you will use a zero-configuration bundler for tiny modules called Microbundle.

Why microbundle?

With Microbundle, tiny modules can be bundled without any configuration, and it offers the following features:

  • Single dependency for bundling with just a package.json
  • ESnext & async/await support through Babel and async-promises
  • Produce highly optimized code for all inputs
  • Zero-configuration TypeScript support
  • Includes built-in Terser compression and tracks gzipped bundle size
  • Creates multiple output formats for each entry (CJS, UMD & ESM)
  • Supports multiple entry modules (*cli.js* + *index.js*, etc) # Building the package ## Install microbundle

To use microbundle, run the command below in your terminal.



npm i -D microbundle


Enter fullscreen mode Exit fullscreen mode

The command generates a node_modules folder in your terminal and a package.json file.

In the package.json, replace the existing code with the code below.



    {
      "name": "capitalizefirstletterofastringpkg",
      "version": "1.0.0",                     
      "type": "module",
      "source": "src/index.js",            
      "main": "dist/index.js",
      "module": "dist/index.module.js",
      "unpkg": "dist/index.umd.js",
      "scripts": {
        "build": "microbundle",           
        "dev": "microbundle watch"        
      },
      "devDependencies": {
        "microbundle": "^0.15.1"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/femakin01/CapitalizeFirstLetterofaString.git"
      }
    }


Enter fullscreen mode Exit fullscreen mode

The provided package.json code is a configuration file used in Node.js projects. Here's an explanation of each key-value pair in the code:

  • "name": "capitalizefirstletterofastringpkg" Specifies the name of the package

  • "version": "1.0.0": Indicates the version of the package

  • "type": "module": Indicates that the project uses ECMAScript modules

  • "source": "src/index.js": Specifies the entry file for the source code

  • "main": "dist/index.js": Indicates the main file that will be used when importing the package

  • "module": "dist/index.module.js": Specifies the module file that will be used in ECMAScript module systems

  • "unpkg": "dist/index.umd.js": Specifies the file to be used in the UMD (Universal Module Definition) format

  • "scripts"

    • "build": "microbundle": Executes the microbundle command to build the package.
    • "dev": "microbundle watch": Executes the microbundle watch command to start a development server that watches for changes
  • "devDependencies": Lists the development dependencies required for the project. In this case, it includes "microbundle": "^0.15.1"

  • "repository": Specifies the repository type and URL of the project

This package.json file is specifically configured for the capitalizefirstletterofastring package, utilizing the microbundle package for building and watching the code.

At this point, your new package.json file should resemble this screenshot and is all set up for local development.

package.json file

Package Development

To create the package that capitalizes the first letter of a string, In the src/index.js file, paste the code below:



    export const Capitalize = ({ str }) => {
      return str.charAt(0).toUpperCase() + str.slice(1)
    }


Enter fullscreen mode Exit fullscreen mode

The code above exports a concise function named Capitalize that takes a string input and returns the same string with the first character capitalized. It achieves this by using str.charAt(0).toUpperCase() + str.slice(1)

Next, try it out and build the package by running



    npm run build


Enter fullscreen mode Exit fullscreen mode

Microbundle produces esm, cjs, umd bundles with your code compiled to syntax that works everywhere.

Publishing the package

To publish your package, run the following command to authenticate yourself:



    npm login


Enter fullscreen mode Exit fullscreen mode

You will be prompted to provide your details, provide the required details and hit enter. To test the login's success, enter the command:



    npm whoami


Enter fullscreen mode Exit fullscreen mode

Your username should be logged into the CLI.

Now, you can proceed to publish your package by running the command below:



    npm publish


Enter fullscreen mode Exit fullscreen mode

Note that you may not be able to publish the random-number-package if someone else already has a package with the same name in the registry. You can change the package's name to something unique to make it publishable. Check here for guides on naming a package.

After the publication is done without error, you can visit your account in the NPM registry to see the package.

Published package

Testing the Package

To test the package, bootstrap a Next.js application by running the command below:



    npx create-next-app@latest


Enter fullscreen mode Exit fullscreen mode

On installation, you'll see the following prompts:



    What is your project named? my-app
    Would you like to use TypeScript with this project? No / Yes
    Would you like to use ESLint with this project? No / Yes
    Would you like to use Tailwind CSS with this project? No / Yes
    Would you like to use `src/` directory with this project? No / Yes
    Use App Router (recommended)? No / Yes
    Would you like to customize the default import alias? No / Yes



Enter fullscreen mode Exit fullscreen mode

After the prompts, create-next-app will create a folder with your project name and install the required dependencies. Next, navigate to the project directory and install the published package by running the command below:



    npm i capitalizefirstletterofastringpkg


Enter fullscreen mode Exit fullscreen mode

Next, in the src/app/page.js replace the content with the following code:



    import React from 'react'
    import { Capitalize } from 'capitalizefirstletterofastringpkg'
    function    page() {
      return (
        <div>  `This is  a Sample Usuage {<Capitalize str={'example'} />}`</div>
      )
    }
    export default page


Enter fullscreen mode Exit fullscreen mode

If you navigate to localhost:3000, you will see the first letter of the string in your package capitalized.

Sample package

Congratulations! You have just successfully created your first React NPM package professionally.

Conclusion

Creating your React component library is a valuable investment for teams or individuals seeking to streamline their development process and ensure project consistency. Following the steps detailed in this guide, you can effortlessly build a library of reusable components that can be shared and utilized across various projects.
Leveraging the capabilities of React and the flexibility of custom components, the possibilities are endless in terms of what you can create and achieve.
Begin constructing your component library today and experience its positive influence on your development workflow!

References

Top comments (3)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Thank you @fruntend 🙌

Collapse
 
starkraving profile image
Mike Ritchie

I want to publish a package with a collection of React hooks and components. The source files are written with .jsx extensions, and they import their own .scss files for styling. Is microbundle still the easiest way to create the build files? Will this result in a /dist folder with the same file structure such that I can import the components in any project that installs this package?