Create NPM package In React.JS

zainbinfurqan

Zain Ahmed

Posted on November 15, 2024

Create NPM package In React.JS

In this article, I'll walk you through the process of creating and publishing an npm package for a React.js application.

First, run the following command:

npx create-react-library react-loader
Enter fullscreen mode Exit fullscreen mode

This will generate a basic React.js application/package. After running the command, you'll see a project structure like this:

React npm example structure

in the src folder, you'll find an index.js file.

React npm example structure

You can either create your library component directly in the index.jsfile, or you can create a new component file in the src folder and export it from the index.js file like this:

React npm example structure

If you're using CSS for your component, be sure to import it into your component file.

Next, if you have a dist folder in your project, delete it. To test if your component is functioning correctly, navigate to the example/src folder.

React npm example structure

In the App.js file, import your component as shown here. This is the same approach you'll use to include this library as an npm package in other projects.

To run the app, execute the following commands:

cd react-loader && npm start
cd react-loader/example && npm start

After testing your library, it's time to publish it.

If you've already set up a repository for your project, simply push the final changes. Otherwise, create a new repository and push your changes.

You also need to create a .npmignore file at the root of your project, which functions similarly to a .gitignore file for NPM. It prevents certain files and folders (like node_modules, .git, .gitignore, etc.) from being published to the NPM registry.

npmignore file

After pushing your changes, run the command npm login. You'll be prompted to open NPM in your browser, where you can log in to your account or sign up if you don’t have one. Then, execute npm publish, which will publish your dist folder to NPM with the version specified in your package.json file.

package.json file

npm package

Once the package is published, you can view it on the NPM website by searching for your package name or by visiting your profile, where all your packages will be listed.

Follow for more You can find me here

💖 💪 🙅 🚩
zainbinfurqan
Zain Ahmed

Posted on November 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Create NPM package In React.JS
javascript Create NPM package In React.JS

November 15, 2024