This is the second part of my "Creating Node modules" series. If you missed the first part, you can access it here.
In this section, we will focus on getting the package.json file ready so that you can create your own package and get it ready to be published.
What's the package.json
The package.json is simply a json file that contains all the information about your module. It will contain the author name and email, the module name, the current version number and most importantly, all the dependencies so that when a user will do a npm install, npm will know what packages to install.
Set some defaults
The first thing you'll want to do is to set some default values for npm. Those will then be pre-populated in your package.json file.
In a terminal window, enter the following. (You will, obviously, want to change the name by your own name).
npm set init.author.name "Joel Lord" npm set init.author.email "firstname.lastname@example.org" npm set init.author.url "http://joel-lord.com"
Once this is done, you will need to create npm user name and password so that you can eventually publish your package. You can do this by running.
Create the file using npm
In order to ensure that everyone has more or less the same format for package.json files, npm included a command-line tool to generate this file. Use npm init and answer the questions to generate your version of the file.
You now have your packages.json which you will need in order to publish stuff on npm. You will notice that we left the git repo empty, you can enter your repo url here if you want to. We also left the test command field empty, we will cover this in part 3 of this series.
Other useful npm commands
Now that you have a package.json, you have to make sure that you keep it up to date. Failure do to so will result in many frustrations by your users. Here are a few tricks to makes you that you always keep it up to date.
When you add a new dependency with npm install, always add the --save argument. This will ensure that this new module you are adding is also added to your package.json dependencies.
Say you wanted to add "yargs" to manage command line options, you should use
npm install --save yargs
This will add a new line for "yargs" in your package.json as well as install the package as it would normally do with a npm install.
Building a new version
When you prepare a new release, you want to be sure that your version number is also updated so that your users are not confused. In order to do so, you can use npm version <type> where the type is either patch, minor, or major. For more information about the meaning of each of the version types, you can check the SemVer guide. This will also create a git tag for you if you have a git repo initialized.
npm version patch
We are now almost ready to publish a new npm module to npm. The final step will be to add unit tests to this modules (although, in theory, you should create the test first). Stay tuned for part 3 of this series.