How to publish a Node.js module on npm#

Before you can publish your Node.js module on npm, you have to create one. If you don't know how to create one, read "Node.js: Writing modules".

Assuming you are done implementing the functionality of your module, create these two additional files in the module directory.

  1. package.json - The module meta data JSON file. Add the name and version properties at the minimum. If you want your package to be used by others, make sure to include the license property. Refer to https://docs.npmjs.com/creating-a-package-json-file for the possible properties in the package.json file.

  2. README.md - Serves as a basic documentation for your module. Use Markdown for formatting the content.

You can run npm init in the project directory to interactively generate the package.json.

~/projects/my-module-abc/
$ npm init

Make sure the contents of the package.json are specified correctly and accuarately.

If you don't have an npm account already, goto https://www.npmjs.com/signup and sign up.

Then, log in to your npm account:

$ npm login
Username: hacksparrow
Password:
Email: (this IS public) captain@hacksparrow.com
Logged in as hacksparrow on https://registry.npmjs.org/.

Run npm publish to publish your Node.js module as an npm package:

~/projects/my-module-abc/
$ npm publish
npm notice
npm notice 📦  my-module-abc@1.0.0
npm notice === Tarball Contents ===
npm notice 209B package.json
npm notice 54B  index.js
npm notice === Tarball Details ===
npm notice name:          my-module-abc
npm notice version:       1.0.0
npm notice package size:  309 B
npm notice unpacked size: 263 B
npm notice shasum:        dbe99d75071b244efcdd8243e90fe51635de759a
npm notice integrity:     sha512-YluHzjIsUCTIN[...]3LCjKahwNhVwg==
npm notice total files:   2
npm notice
+ my-module-abc@1.0.0

Version 1.0.0 of my-module-abc has been published on npm.

If you wish to include repository information about your module, add the information in its repository property as shown below.

./package.json
  "repository": {
    "type": "git",
    "url": "https://github.com/hacksparrow/my-module-abc.git"
  }

If you had already initialized the module directory as a git repository, npm init would have already added the repository details. No further actions are required.

Then initialize the project directory as a git repository and add a remote named origin pointing to the location of your remote repository.

~/projects/my-module-abc/
$ git init
$ git remote add origin git@github.com:hacksparrow/my-module-abc.git

Summary#

Creating an npm package is just a matter of adding the package.json file in the Node.js module directory. The package can then be published using the npm publish command.

References#

  1. Node.js: Writing modules
  2. npm - Contributing packages to the registry
  3. npm - package.json
  4. npm - publish
Tweet this | Share on LinkedIn |