Post

How to Build and Publish an npm Package

Updated on September 15, 2020
    Default avatar

    By Akinjide Bankole

    How to Build and Publish an npm Package

    This tutorial is out of date and no longer maintained.

    Introduction

    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 of 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.

    • 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

    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!

    Setup

    1. Create an empty directory and initialize it as an npm package using npm init or npm init --yes, if you’re feeling lazy. It will ask you to create your package.json file.
    1. mkdir acronym && cd acronym
    2. 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):
    1. touch index.js
    2. 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:

    1. touch example.js
    2. 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);
      });
    
    1. node example.js
    2. # 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.

    Go to the package directory:

    1. cd ~/<projects>/acronym

    Create a global symlink:

    npm link
    

    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>.

    Go to some other package directory:

    1. cd ~/<projects>/<some-other-node-project>

    Link-install the acronym package:

    1. npm link acronym

    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.

    1. npm whoami
    2. # 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.

    1. npm publish
    2. # + acronym2@1.0.0

    Unpublish

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

    1. npm unpublish
    2. # - 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.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about us


    About the authors
    Default avatar
    Akinjide Bankole

    author

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel