How to Test an npm package locally


I needed a way to test my npm package locally before publishing it.

Suppose we had a package.json that looked like this:

{
  "name": "my-package-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js"
}

Let’s say this file lives at ~/my-package-name/package.json.

First, we can navigate to this directory in the terminal.

cd ~/my-package-name

Then, we can run:

npm link

This command creates a global, symbolic link that is accessible by any project. It essentially functions as a global npm module.

For instance, we can run create-react-app anywhere after running npm install -g create-react-app.

Similarly, we can run npm link my-package-name anywhere after running npm link in ~/my-package-name.

Let’s go to the project that we want to use to test this package.

cd ~/some_project

Then, link-install this package.

npm link my-package-name

Note that the name of the link will be the name in package.json, not the directory name.

Because of the symbolic link, changes in ~/my-package-name will be reflected in ~/some_project, no need to rebuild every iteration.

const mypackagename = require("my-package-name");
import mypackagename from "my-package-name";