Making a Node.js Project into an NPM Package

We recently published an NPM package, backand-hosting-s3, intended to sync a local project folder to Backand AWS S3 bucket. This bucket serves our users as a static web site for their AngularJS projects. The package is to be used in Gulp files and in a forthcoming Backand CLI.

After completing development, while trying to publish the package, we encountered a few salient holes in the vast amount of guides and articles.

We fill you in here on these salient points to make your life easier when trying to publish an NPM package.

Structuring Package.json

After initialise it with:

   npm init

We found two important points worthy of mentioning.

List the Files

          "files": [

            "backand_sync_s3.js",

            "config.js"

          ],

Define the bin File

The bin file is the entry point to the package that will be put in node_modules/.bin folder when the package is installed. Enabled usage of the package in a command-line mode.

Specify it with:

          "bin": {

            "backand_sync_s3": "./backand_sync_s3.js"

          },

Testing the Package

  1. In the project folder, pack the folder into a tgz file, in our case, backand-hosting-s3-1.0.0.tgz,

    npm pack
    
  2. Go to another folder, say myApp. Make sure all dependencies of your package were including in its package.json, by removing the node_modules folder.

  3. Install your package:

    npm install ~/backand-hosting-s3/backand-hosting-s3-1.0.0.tgz
    
  4. Write a short program that will test your package. In our case, the following gulp file, will do:

     var gulp = require('gulp');
    
     var backandSync = require('backand-hosting-s3');
    
     gulp.task('clean', function() {
    
         return backandSync.clean();
    
     });
    

Install gulp, (if not installed globally on your system),

  npm install gulp

And test the usage of the package with,

      node_modules/gulp/bin/gulp.js

If any of your dependencies were not included in your package.json you will get an error and the program will crash.

Publishing The Package

We give you here the crucial instructions, taken from the NPM guide.

  1. Commit your code to GitHub

  2. Register at NPM, and obtain a username and password

  3. In the package folder, login to NPM,

    npm login

  4. Publish the package

            npm publish
    

Updating The Package

  1. Do, npm version <update_type>, where update_type is one of the semantic versioning release types, patch, minor, or major

  2. Commit your code to GitHub, as the previous instruction modified the version number in package.json

  3. Publish the updated package

     npm publish