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
This will generate a basic React.js application/package. After running the command, you'll see a project structure like this:
in the src
folder, you'll find an index.js
file.
You can either create your library component directly in the index.js
file, or you can create a new component file in the src
folder and export it from the index.js
file like this:
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.
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.
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.
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
Top comments (0)