This guide will walk you through the process of publishing a React component as an NPM package. Publishing packages on the NPM registry comes with several benefits, including code sharing, collaboration, and reusability within your projects and the wider developer community.
Before you begin, make sure you have the following prerequisites installed:
- Node.js
- npm
- npm account (Create one if you don't have an account)
Ensure that you have a unique name for your package. You can verify the uniqueness of your proposed package name on the npm website or through the terminal using the following command:
npm search <your-package-name>
To initialize your package, run the following command, replacing with your desired package name:
npx create-react-library <your-package-name>
{
"name": "demo",
"version": "1.2.7",
"description": "Demo",
"author": "Vijay Joshi",
"license": "MIT",
"repository": "https://github.com/thevijayjoshi/npm-react-publish",
"main": "dist/index.js",
"module": "dist/index.modern.js",
"source": "src/index.js",
"engines": {
"node": ">=10"
},
"scripts": {
"build": "microbundle-crl --no-compress --format modern,cjs",
"start": "microbundle-crl watch --no-compress --format modern,cjs",
"prepare": "run-s build",
"test": "run-s test:unit test:lint test:build",
"test:build": "run-s build",
"test:lint": "eslint .",
"test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
"test:watch": "react-scripts test --env=jsdom",
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
},
"peerDependencies": {
// Add your peerDependencies here
},
"devDependencies": {
// Add your devDependencies here
},
"files": [
"dist"
]
}
Make sure to add the dependencies your component needs in the peerDependencies section.
Here's the recommended folder structure:
- dist
- example
- node_modules
- src
- Components
- DemoComponent
- index.js (Write your component code here)
- index.js
- index.js
- .editorconfig
- .eslintignore
- .eslintrc
- .gitignore
- .prettierrc
- .travis.yml
- package-lock.json
- package.json
- README.md
// src/index.js code
export * from './Components';
// src/components/index.js
export { default as DemoComponent } from './DemoComponent';
To publish your package, follow these steps:
1.Login(If you are doing 1st time):
npm login
2.Build your package:
npm run build
3.Publish your package:
npm publish
Hooray! Your React component is now published as an NPM package.
If you want to make changes after publishing, update the version in your package.json file, and then run the following commands:
1.Build your package:
npm run build
2.Publish your package:
npm publish
That's it! Your changes will be reflected in the latest version of your package on NPM.