Create and publish an NPM module
Code modularization, achieved in one way or another, is a technique a good developer must aim for because it helps keeping things small, well-tested and organized. And of course, it follows the DRY directive. So as a Node.js developer (and maybe contributor to the Open Source), creating and publishing an NPM module is one of those steps you will eventually face.
Probably if any Node.js developer would have to pick an indispensable tool of the ecosystem, npm would win by far. Its greatness resides in how much easy is to build applications using on of several modules, each of them providing one certain functionality, as if they were building bricks, picking the right tool for each task.
But, how difficult is the process of creating an NPM module? Well, here is a cheat sheet to get this done:
- Create a directory with the name of the module and place your code in it. How you structure your content is up to you. The index file will define your external API (module’s exports), the functionality other developers can reach of your module.
If you never logged in into npm (usually you don’t need to do it unless you want to push some content into NPM repository), this would be your next step:
$ npm adduser $ npm login
Initialize your module and fill in the required information:
$ npm init
Don’t forget to install all your dependencies so they appear in the package.json manifest:
$ npm install whaterver-module --save
Once you have set up your package.json file, you’re ready to make it public. Increase the version number of you module and publish it:
$ npm publish
Now you’ll be able to find it in the NPM repository:
$ npm search test-module-dpecos
Optionally, tag your GIT repository with current version number. It makes easier to guess what was included with each release of your module.
And that’s it!, your package will soon appear in NPM registry search results (it it hasn’t already), allowing other developers to find and use it.
Whenever you want to publish and update of one of your already published modules, these are the steps you should follow:
- Increase your module’s version number
- Publish it again
- Optionally, tag your GIT repository with current version number
You have to take care about version numbers:
- You can’t repeat them
- You can’t publish a lower version number than the previously published version
- You can follow any scheme to designate your version number, but there are some of them considered standard
But sometimes, software gets old, deprecated or replaced by a better one. If, sadly, this is the case for your module, you can remove it from NPM registry with these command:
$ npm unpublish
And it will be gone forever 🙁
If you want to get an deeper knowledge of npm commands, I recommend you to visit the official CLI docs.