We're live-coding on Twitch! Join us!
How to Build and Publish an npm Package

How to Build and Publish an npm Package

Code

Every Node.js developer knows that when creating a new Node project, one of the very first things you'll do is type npm init and answer couple questions, and then install dependencies and devDependencies.

In this article, we'll look at creating an npm package that can be installed as a dependency and publish to npm.

What is a package and module?

npm has specific definitions of packages and modules, which are easy to mix up. I'll like to discuss these definitions and explain certain default files.

Note

  • A package is a folder containing a program described by a package.json file that defines the package.
  • A module is a folder with a package.json file, which contains a main field, that enables loading the module with require() in a Node program.
  • The node_modules folder is the place Node.js looks for modules.

Generally, most npm packages are modules. However, there's no requirement that an npm package should be a module. There are CLI packages, that contain only executable command-line interface(CLI) and don't provide a main field to be loaded with require(), these type of package is not a module.

In the context of a Node program, the module is loaded from a file. For example, in the following program:

    var acronym = require('acronym');

we can say that "variable acronym refers to the acronym module".

Prerequisites

Note

  1. Important words are highlighted.
  2. Bold words emphasis a point.
  3. Previous / Next code appears like this . . . .

This project requires a fair understanding of Javascript Promises and Callbacks and Node.js v6.11.0 LTS or higher to support some ECMAScript 2015 features. You can follow this tutorial or view the full code for this tutorial on Github.

Now that you have completed the prerequisites, let's start!

Essential Reading: Learn React from Scratch! (2019 Edition)

Setup

  1. Create an empty directory and initialize it as a npm package using npm init or npm init --yes, if you're feeling lazy. It will ask you to create your package.json file.
    $ mkdir acronym && cd acronym
    $ npm init --yes

  1. Navigate to your directory, a package.json file should exist like this :
    {
          "name": "acronym",
          "version": "1.0.0",
          "description": "",
          "main": "index.js",
          "scripts": {
              "test": "echo \"Error: no test specified\" && exit 1"
          },
          "author": "",
          "license": "ISC"
    }
  1. By default, a main field will get created. The main field is a module ID, the entry point (main script) to your program. That is, if a user installs this package, and then does require("acronym"), the main module exports object will be returned.
  2. Edit the package.json file to look like this, if you want to add information for the author field, you can use the format Your Name <email@example.com> (email is optional):
    {
          "name": "acronym",
          "version": "1.0.0",
          "description": "Transform sentences to acronyms.",
          "main": "index.js",
          "author": "Akinjide Bankole <r@akinjide.me>" // optional
    }
  1. Let's start creating our script file and open with Sublime Text (or Atom, VIM, WebStorm) :
    $ touch index.js
    $ open . -a 'Sublime Text'

Getting started

    "use strict";

    module.exports = function acronym(sentence, callback) {

    }

module.exports encapsulates and allows the acronym function to be with other code. The acronym function takes two parameter, a string data type e.g. "for your information" and a callback function.

    . . .

    return new Promise((resolve, reject) => {

    });

    . . .

We define and return an instance of the Promise class. A Promise is an object which can be returned synchronously from an asynchronous function, it may be in one of 3 possible states: fulfilled, rejected, or pending, and produces a single value some time in the future.

  • Fulfilled will be called when resolve() is called.
  • Rejected will be called when reject() is called.
  • Pending is either not yet fulfilled or rejected.
    . . .

    if (sentence.length === 0) {
        reject('String, Please! e.g. "for your information"');
        return callback('String, Please! e.g. "for your information"');
    }

    . . .

The if statement checks for the length of the sentence parameter, if the condition is true, we reject with an error message (String, Please! e.g. "for your information"). The return keyword before the callback, immediately breaks out of the function call, returning the callback function with an error message.

    . . .

    else if (typeof sentence === 'function') {
        callback = sentence;

        reject('¯\\_(ツ)_/¯');
        return callback('¯\\_(ツ)_/¯');
    }

    . . .

The else if statement checks if the user passes in a function as the first parameter instead of a string, if the condition is true, we assign the function to callback and reject with an error message (¯\\_(ツ)_/¯).

    . . .

    else {
        const words = sentence.split(' ');
        const acronym = words.map((word) => word[0]);

        . . .
    }

The else statement will be the default if none of the conditions above was satified. The first line, we .split the sentence into an array ['for', 'your', 'information']. The second line, we .map and return an array, with the first character of each word ['f', 'y', 'i'] and assign to variable acronym.

    . . .

    else {
        . . .

        resolve(acronym.join(''));
        return callback(null, acronym.join(''));
    }

We .join and resolve the acronym array, and return the callback function with null as error and the joined acronym array.

So far we have created the package.json, index.js file. Let's create a script file, open with Sublime Text (or Atom, VIM, WebStorm) and test our index.js:

    $ touch example.js
    $ open example.js -a 'Sublime Text'
    const acronym = require('./'); // require the `index.js` file from the same directory.

    acronym('for your information', (err, resp) => {
        if (err) {
            console.log(err);
        }

        console.log(resp);
    });
    $ node example.js
    # fyi

Test

Working on a package and testing iteratively without having to continually rebuild or publish to npm registry has been a major concern to package authors. npm link is an handy way of linking and testing packages locally before publishing.

npm link basically links a package folder to the global node_modules directory. Package linking is a two-step process. First, you'd npm link the pacakge folder, creating a symlink in the global node_modules.

Note

  • Replace <projects> with the folder where the acronym project exists previously.
  • Replace <some-other-node-project> with an exisiting node project or create a new one for testing.

    $ cd ~/<projects>/acronym
    # go to the package directory

    $ npm link
    # create a global symlink

Next, in <some-other-node-project>, npm link acronym creates a link from the globally installed acronym to the node_modules directory of the <some-other-node-project>.

    $ cd ~/<projects>/<some-other-node-project> 
    # go to some other package directory.

    $ npm link acronym 
    # link-install the acronym package

Now the node_modules directory should look like this:

    ├─ node_modules   
    │   ├─ acronym -> ../../.nvm/versions/node/v4.6.1/lib/node_modules/acronym      
    ├─ package.json

With npm link, requiring the local project becomes easy and we publish to npm when we are entirely ready.

Here is a link to read further: https://medium.com/@the1mills/how-to-test-your-npm-module-without-publishing-it-every-5-minutes-1c4cb4b369be

We've tested the module locally, now we publish.

Publish

Note

  • Make sure that everything in the directory is vetted, or ignored using .gitignore.
  • Make sure that there isn't already a package with the same name, if there's a an exisiting project you'll get an error has below.

As I mentioned, we'll be publishing this package to the npm registry so that it can be installed by name. Before we publish make sure your acronym directory looks like this:

    ├─ acronym   
    │   ├─ index.js
    │   ├─ example.js
    │   ├─ package.json       

As with every registry, you must have a user on npm registry. If you don't have one, create it with npm adduser or using npm site. If you've created using npm site, use npm login to store the credentials.

Use npm whoami to ensure that the credentials are stored.

    $ npm whoami
    # akinjide

Use npm publish to publish the package. You should see the package information when you visit https://npmjs.com/package/<package>. Replace <package> with the package name.

    $ npm publish
    # + acronym2@1.0.0

Unpublish

If you'd like to remove your package from the npm registry, use npm unpublish to publish the package.

    $ npm unpublish
    # - acronym2@1.0.0

Updating

When you make changes to your code and want to update the package you'll need to update the version of the package. Use npm version <update_type>, where <update_type> is a sematic versioning release type patch, minor or major. After updating the version number, you'll need to publish the package again, use npm publish.

Conclusion

Congrats! You now know how to build a node module, make it a package and publish to the npm registry. Feel free to use the code above and contributions are welcome.

Make sure to leave any thoughts, questions or concerns in the comments below. I would love to see them.