How to Create an NPM Package

Advertisement

Advertisement

Intro

This is a quick guide to creating a Node.js package for npm. Full package.json documentation available from npmjs.com.

Start a package

npm init

This will prompt you for some things like name and version, then generate a package.json in your current directory. For license, you can use GPL-3.0 for GNU General Public License v3.

Add extras

Full list of options at package.json documentation.

Dependencies

Add run-time and development only dependencies.

npm install --save something-needed-to-run
npm install --save-dev something-only-for-dev

Run scripts

Run scripts can be run with npm run <script_name>. They are shell commands that run in your system shell (e.g. bash)

  "scripts": {
    "build": "tsc",
    "clean": "rm lib/*",
    "start": "npx nodemon server.js"
  },

Static files

Add any other supporting files like static images.

  "files": [
    "lib/**/*"
  ],

Bin executables

If you have any commands you want to be able to invoke directly, like a regular executable, you want to add a bin entry. Bin executables get launch scripts created automatically so you can run them directly.

  "bin": {
    "myprog": "bin/myprog.js"
  },

This would run with myprog or node_modules/.bin/myprog in the system shell.

Git repo

  "repository": {
    "type": "git",
    "url": "https://github.com/Me/Project.git"
  },

Example package.json

The package.json will look something like this:

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "test only",
  "author": "",
  "license": "GPL-3.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/Me/Project.git"
  },
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "bin": {
    "myprog": "bin/myprog.js"
  },
  "files": [
    "lib/**/*"
  ],
  "devDependencies": {
    "something": "^4.4.0"
  },
  "dependencies": {
    "something": "^4.17.2"
  }
}

Uploading to npmjs.org

First, login. If it prompts you for 2-factor code from your authenticator app, it likely just sent you an email with the code. After logging in, it stores a token in ~/.npmrc.

npm login  # Stores token in ~/.npmrc

You only need to login once, but you need to push anytime there are changes and you increment the version number.

npm publish

Installing from npmjs.org

Install the package using the same name you published it under.

For example:

npm install mypackage

References

Advertisement

Advertisement