Here's a step-by-step guide on how to create a React or JavaScript component and publish it to the npm repository.
1. Create Your Component
First, initialize a new project and set up a simple component.
mkdir my-component
cd my-component
npm init -y # Creates a package.json file
Now, create your component inside src/MyComponent.js
:
import React from "react";
const MyComponent = ({ text }) => {
return <h1>{text}</h1>;
};
export default MyComponent;
2. Configure package.json
Edit package.json
to include:
{ "name": "my-awesome-component",
"version": "1.0.0",
"main": "src/MyComponent.js",
"dependencies": { "react": "^18.0.0" }
}
3. Build the Component for Distribution
To make it usable in other projects, bundle it using tools like Webpack or Rollup.
Example with Rollup:
npm install rollup rollup-plugin-babel @babel/preset-env @babel/preset-react --save-dev
Create rollup.config.js
:
import babel from "rollup-plugin-babel";
export default {
input: "src/MyComponent.js",
output: {
file: "dist/index.js",
format: "cjs"
},
plugins: [
babel({
presets: ["@babel/preset-env", "@babel/preset-react"]
})
]
};
Run the build:
npx rollup -c
4. Publish to npm
1️⃣ Login to npm (if not logged in):
npm login
2️⃣ Publish the package:
npm publish
3️⃣ Install it in any project:
npm install my-awesome-component
Best Practices for npm Packages
✅ Use semantic versioning (1.0.0
, 1.1.0
, etc.).
✅ Write documentation (README.md
).
✅ Include a license (MIT
, Apache
).
No comments:
Post a Comment