Forking, Modifying, and Publishing NPM Packages
Brandon Le
Brandon Le
For those almost-perfect packages
--
Sometimes, you’ll come across a nearly perfect npm package that does almost everything you want. Or perhaps out of all the great features it has, it implements one that just doesn’t fit your web app.
And in some of those cases, you may be able to fork it, modify it, and submit a pull request if the feature aligns with that project’s goals.
But for those times where a merge is highly unlikely, you can still fork, modify, and publish your own version of the npm package so you can use it in your own live apps.
Good to know beforehand
- You’ll need to sign up for an npm account.
Setup
- Fork the repo and clone it to your computer.
- Make the changes you want to the package’s source files.
- Update the package.json name (must be unique on npm) and version number. If this is a minor fork mostly for yourself, I’d recommend using the naming convention ‘@yourUsername/pkgName’.
- Commit your changes.
- In your terminal
npm login
with your username and password. You’ll also confirm your public email address. - Run
npm publish --access public
. The ‘–access public’ amendment is only needed if you use the ‘@yourUsername/pkgName’, and if it’s the package’s first publication. Subsequent updates to the do not require the flag.
Updates
- Update the package.json version number.
- [Only if necessary] Build with
npm run build
oryarn build
, then runnpm update [package name]
to update the package. - Else, run
npm publish
.
Common Errors
Code: 402 You must sign up for private packages : @yourUsername/pkgName
: You need to append--access public
to the end of `npm publish.
Tips
- When testing new changes, I’ll start by opening the npm_modules folder and editing the npm package directly in my project directory. This way, I don’t have to edit the actualy npm package files, publish to npm, update the package in my project, and test.