circlehq/email-builder
How to Publish a React Package to npm
This guide explains how to set up, build, and publish a React package to npm using Babel.
Prerequisites
Make sure you have the following installed:
1. Initialize Your Package
Start by creating a package.json file for your project if you don't have one already:.
- Prepare Your Package
Before publishing, ensure you have a package.json file in the root of your project. You can create one by running:
npm init
This will prompt you for information such as the package name, version, and entry point. Make sure to fill it out correctly.
1.1 Package Name
- For a public package, use a unique name, e.g.,
your-package-name.
- For an organization package, use a scoped name, e.g.,
@your-org/your-package-name.
1.2 Add a Build Script (Optional)
If you are using TypeScript, Babel, or another compiler, add a build script in your package.json:
"scripts": {
"build": "your-build-command",
"prepublishOnly": "npm run build"
}
This ensures that your package is built before publishing.
2. Add an .npmignore File
Create a .npmignore file to exclude unnecessary files from your published package. Common exclusions include:
/node_modules
/tests
/src
/*.log
This prevents unnecessary files from being included in the npm package.
3. Login to npm
If you are not already logged in, log in to npm using:
npm login
You'll be prompted for your npm username, password, and email.
4. Publish Your Package
To publish your package to npm, run:
npm publish
For scoped packages (e.g., @your-org/your-package-name), you must specify public access:
npm publish --access public
5. Update Your Package Version
To update and publish a new version of your package:
-
Update the version in package.json (e.g., from 1.0.0 to 1.0.1).
-
Run the build script, if necessary:
npm run build
-
Publish the updated package:
npm publish
For scoped packages (e.g., @your-org/your-package-name), you must specify public access:
npm publish --access public
6. Verify the Package
You can verify that your package was published successfully by checking it on the npm website:
npm info your-package-name
Or visit npmjs.com and search for your package.
By following these steps, you will successfully publish your package to npm.
7.Updating Your Package
When you need to publish an updated version of your package:
Increment the version in package.json.
Rebuild the package:
npm run build
Publish the updated package:
npm publish
Conclusion
By following these steps, you will be able to successfully publish your React package to npm. Don't forget to update the version each time you make changes and republish!