paint-brush
How to Publish a React Component as a Package to Npmby@jamezjaz
14,565 reads
14,565 reads

How to Publish a React Component as a Package to Npm

by James Chigozie OdufuJuly 12th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Publishing a React component as an NPM package is a great way to share your code with the wider community. It’s possible to publish packages as public as well as private packages on the NPM registry. The create-react-library command initializes your project to be published along with an example app.
featured image - How to Publish a React Component as a Package to Npm
James Chigozie Odufu HackerNoon profile picture

First, I would like to highlight some of the numerous benefits of publishing packages to the npm registry:


  • Publishing a package on npm allows developers to share their code and libraries with the wider community, making it easily accessible and reusable, thereby fostering collaboration and improving the overall development ecosystem.


  • Within an organization/company, it allows for efficient code sharing and reuse across projects, promoting modularity and consistency in development practices, facilitating collaboration among team members, simplifying version management, and ensuring secure access to proprietary or sensitive code within a controlled environment. This article will guide you through the process of publishing a React component as an NPM package



Prerequisites

  • Node

  • npm

  • npm account (You need to create one if you don’t have an account already. Create an npm account at https://www.npmjs.com/ free of charge).


The Business Proper: Private and Public Packages

I’d like to let us know that it’s possible to publish packages as either public or private packages on the npm registry.


  • Public packages: These are intended for open-source projects or libraries that can be accessed and used by anyone. These packages are discoverable and can be installed by anyone using the npm install command.


  • Private packages: These are meant for proprietary code or internal projects within an organization. These packages are not publicly accessible or discoverable on the npm registry. Instead, they are shared with specific users or teams who have been granted access permissions. These often require authentication to access and use.


Now, let’s jump into the business proper!

I need to choose a name for my package, it must not be something special, I mean it could be anything but bear in mind it must be unique.

Selecting a unique package name is crucial. To confirm the uniqueness of your proposed package name on npm, visit the npm website and search for your proposed package name, and that’s it!

Alternatively, you can confirm the uniqueness of a package name via the terminal by running this command npm search <your-package-name>


I have chosen fallback-avatar-hex as my package name because;


  • I intend to publish a hexagonal fallback avatar component for users without profile photos.

  • I can confirm that my package name does not already exist in the npm registry.


Initializing the Package

I have to run the below command to initialize my package: npx create-react-library fallback-avatar-hex


Then I was prompted to key in the letter y to proceed.


Then, I was prompted to answer a couple of questions. Thankfully, most of these questions are already pre-filled, you need to keep hitting the Enter key. However, you can change them if you wish. Use the arrow keys for the Package Manager and Template fields to choose your choices. It might take a little while to complete the whole process, just sit back, relax, and enjoy the show :)


Did you notice that I ran npx create-react-library fallback-avatar-hex and not npx create-react-app fallback-avatar-hex ?


This is why:

Using create-react-library offers several advantages. Firstly, it allows you to initialize your project for publication, providing you with an example app that facilitates package testing. Additionally, it sets up your project as a local Git repository, enabling easy integration with GitHub or any other version control system by simply adding the URL for your remote repository.


Below is what the structure of the app looks like when the create-react-library command is complete.


create-react-library structure



The src/ houses the ExampleComponent component which is like a placeholder for my FallbackAvatarHex component. The example/ houses the test app for testing the FallbackAvatarHex component.


The create-react library creates a React app in such a way that it has the example app and the main app in one React app, this is like a two-in-one React app.


Before adding my FallbackAvatarHex component, I’d like to show us see the scripts section of my package.json in the src/ dir.


the scripts section of my src/package.json



Now, let’s cd into fallback-avatar-hex and start the dev server.


Fire up your terminal and run this command: cd fallback-avatar-hex && npm start

On a new terminal, run the below command: cd fallback-avatar-hex/example && npm start

The first command watches the src/ and recompiles it into the dist/ folder when you make changes, hence the start section of the scripts object in the src/package.json file.

The second command runs the example app that links to your package.


Adding My FallbackAvatarHex React Component

A close look at the src/ dir reveals an index.js which held the ExampleComponent component which is called in the App.js file of the example app.


I’ve got at least two ways to modify the index.js file, viz:

  • Get rid of the ExampleComponent component and replace it with my FallbackAvatarHex component and export it as default export like this: // src/index.js


    FallbackAvatarHex component in src/index.js



OR


  • Create a new file, FallbackAvatarHex.js in src/ dir, import and export as default in src/index.js file like this: // src/FallbackAvatarHex.js


    FallbackAvatarHex component in src/FallbackAvatarHex.js


I need to make sure that my component is being imported from the FallbackAvatarHex.js file and exported as well, so that any project that uses my package, will get to use my component accordingly. // src/index.js


NB:

  • If your package requires a CSS file, ensure it’s defined within the src/ dir and it’s imported in the FallbackAvatarHex component.

  • If using SASS, install it as a dev dependency and ensure it’s included in the peerDependencies section of the package.json like this:

    peerDependencies and devDependencies sections of package.json


  • Essentially, the peerDependencies section of the package.json compels the app that will consume our package to install the dependencies therein.

  • Currently, the source section of my package.json looks like this: "source": "src/index.js", If you want, you can modify the source section, say for example: "source": "src/package.js", But ensure that your component (FallbackAvatarHex component in my case) is defined or imported and exported as default in the src/pacakge.js file as the case may be.


Testing the Package

I need to ensure the package is working as expected before publishing it to the npm registry. To do this, I have to return my FallbackAvatarHex component in the App.js file of the example app like this:


Testing the FallbackAvatarHex component in the App.js file of the example app



The example app is currently running on port 3001, opening the app on http://localhost:3001, shows something like this:


FallbackAvatarHex avatar displayed on the browser



Publishing My Package

First, I need to add/modify a couple of things before publishing my component to npm.


  • .npmignore file: This file works just like the .gitignore file, it prevents some specified files and folders (such as node_modules, .git, .gitignore, etc) from being published to the npm registry. .npmignore fie looks just like this:


    .npmignore file



  • package.json file: Add the main and module fields if they do not already exist. Update the author field if you wish. Add the homepage and the keywords fields, these are optional though. You can add a link to your project if it has one using the homepage field. Since mine doesn’t have it yet, I’ll update it to coming soon.

    You can give the npm search directory keywords to attach to your project so that people using the npm search engine can find your project more easily using the keywords field. It takes an array of words as an argument.


    Do not forget to update the repository field accordingly, this property links your repository link such as the GitHub link to your package on npm.


    Here’s what my package.json file looks like now:

    package.json


  • README.md file: Finally, updating the README.md file, highlighting the prerequisites as well as the package usage would amazing. This serves as the package’s docs.

    Before publishing the package, you might want to push your package to a remote repository assuming you’ve created one already.

    Since I’ve created a GitHub repository for my package, I’ll have to run the following commands:

    git remote add origin https://github.com/jamezjaz/Fallback-Avatar-Hex.git # Sets the new remote for the local repo git add . git commit -m 'Initial Commit' git push -u origin main # Pushes the changes to the remote repository


    Next is to run npm login to log into npm. Ensure you already have an account on npm. This command will request your username and password as well as an OTP if you enabled a 2FA.


Then run npm run build, this optimizes and creates a production build for your package. I recommend running this every time you modify your package.


And finally, run npm publish, this command uploads your package to the npm registry. To confirm that it’s successful, navigate to https://www.npmjs.com/settings/your-username/packages to see all your published packages.

Alternatively, navigate to the npm website and search for the package name (fallback-avatar-hex in my case) using the search bar, and there you go :)


At this stage, you or anyone else can easily install and use the package on other projects/apps by running npm install --save fallback-avatar-hex or simply npm i fallback-avatar-hex


Remember to always increment the version each time you wish to publish again.




You can always reach me via:

Email: [email protected] LinkedIn: https://www.linkedin.com/in/jamesgozieodufu/

Merci pour votre temps!