How to Build and Publish Your First React NPM Package
Tags: react, npm, javascript, tutorial
Published: 2023-06-09 18:47:29

Building and publishing your first [Node Package Manager(NPM)](https://www.npmjs.com/) 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:


- [A GitHub account](https://github.com)
- [Node.js](https://nodejs.org/en/) ( v10+) installed
- [NPM account created](https://www.npmjs.com)
- Basic understanding of JavaScript


# What is NPM

[NPM](https://www.npmjs.com/) is a powerful tool transforming how developers share and manage JavaScript code. It is the default package manager for [Node](https://nodejs.org/en)[.js](https://nodejs.org/en), 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](https://bit.dev), [Storybook](https://storybook.js.org/), [Lerna](https://lerna.js.org/), and [TSDX](https://github.com/jaredpalmer/tsdx#quick-start). However, for this tutorial, you will use a zero-configuration bundler for tiny modules called [Microbundle](https://github.com/developit/microbundle). 

## Why microbundle?

With [Microbundle](https://github.com/developit/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](https://babeljs.io/) and [async-promises](https://github.com/rpetrich/babel-plugin-transform-async-to-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.

```javaScript
npm i -D microbundle
```

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.

```javaScript
    {
      "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"
      }
    }
```

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](https://paper-attachments.dropboxusercontent.com/s_EF256C712A38BF7203F4A558947AD38F0CC3BFAF10749896DDA1DD8044F55021_1685400393046_Screenshot+2023-05-29+at+23.42.04.png)

## Package Development

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

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

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 

```javaScript
    npm run build
```

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: 

```javaScript
    npm login
```

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

```javaScript
    npm whoami
```

Your username should be logged into the CLI.

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

```javaScript
    npm publish
```

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](https://paper-attachments.dropboxusercontent.com/s_EF256C712A38BF7203F4A558947AD38F0CC3BFAF10749896DDA1DD8044F55021_1685398402923_screencapture-npmjs-package-capitalizefirstletterofastringpkg-2023-05-29-23_12_02.png)

# Testing the Package

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

```javaScript
    npx create-next-app@latest
```

On installation, you'll see the following prompts:

```javaScript
    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

```

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:

```javaScript
    npm i capitalizefirstletterofastringpkg
```

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

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

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


![Sample package](https://paper-attachments.dropboxusercontent.com/s_EF256C712A38BF7203F4A558947AD38F0CC3BFAF10749896DDA1DD8044F55021_1685399933905_Screenshot+2023-05-29+at+23.38.38.png)


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
- [Create react library documentation](https://github.com/transitive-bullshit/create-react-library#readme)
- [Build and publish your first NPM package](https://medium.com/the-andela-way/build-and-publish-your-first-npm-package-a4daf0e2431)
- [How To Build Your Own React Components Library](https://blog.openreplay.com/how-to-build-your-own-react-components-library/)