5 Jan 2020

Build and Publish NPM Package

What is NPM

NPM (Node Package Manager) serves two primary functions: it’s an online repository for publishing open-source Node.js projects, and it’s a command-line utility for package installation, version management, and dependency management. Thousands of Node.js libraries are available through npmjs.org.

Building the package

Requirements

To build and publish an NPM package, you need the npm command-line tool, which comes bundled with Node.js. Download Node.js from nodejs.org, then verify installation with npm --version.

The package.json file

The most important file for an NPM package is package.json. Create your project directory and initialize it:

mkdir random-number-generator
cd random-number-generator
npm init

npm init prompts you with questions about your package, and generates a package.json with basic metadata. The main field specifies which file loads when the package is imported.

Adding project code

Create an index.js file with your package code:

function randomNoGenerator(min, max) {
  if (typeof max !== 'number' && typeof min !== 'number') {
    min = 0;
    max = 1;
  }
  return (Math.random() * (max - min)) + min;
}

module.exports = randomNoGenerator;

Use module.exports to specify what’s available when others import your package.

Publishing the package

Authenticate

Create an NPM registry account at npmjs.com, then authenticate via the CLI:

npm login
npm whoami

Publish

Make sure your package name is unique (check npmjs.com for existing names first), then:

npm publish

Testing

Install and use your published package to verify it works:

mkdir random-number-test
cd random-number-test
npm install random-number-generator --save
touch test.js
const randomNumberGenerator = require('random-number-generator');
console.log(randomNumberGenerator(5, 10));

Run it with node ./test.js to confirm.