How to test an npm package locally

By

Learn how to test your own npm package locally before publishing, using npm link, a file: dependency, or workspaces to consume it from another project.

~~~

If you want to develop your own npm package, you first have to test it locally.

I had this need with a project that I wanted to modularize.

I had a package I called, as an example, flaviocopes-common-database.

I prepended flaviocopes- to give it a unique namespace.

Inside the package I added a package.json file with the module name in the name property and a few dependencies:

{
  "name": "flaviocopes-common-database",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "pg": "^8.0.2",
    "sequelize": "^5.21.6"
  }
}

Then I ran

npm link

This created a symbolic link in the /usr/local/lib/node_modules/ folder, that contains the global npm packages in the system, the ones installed using npm -g, to be clear.

I had

/usr/local/lib/node_modules/flaviocopes-common-database

Pointing to the local file I had in

/Users/flavio/dev/code/flaviocopes-common-database

If you installed Node with nvm, or you changed the npm prefix, the folder is a different one. npm prefix -g prints it, and the link ends up in its lib/node_modules/ subfolder.

Now in another project I wanted to use this module, so I ran

npm link flaviocopes-common-database

and I was able to import it in the Node.js code using the usual require() syntax:

const database = require('flaviocopes-common-database')

You can also do the two steps at once, from the project that uses the package, by passing the path to the package folder:

npm link ../flaviocopes-common-database

Option 2: a file: dependency

If you just want to try the package in one project, install it by passing its path:

npm install ../flaviocopes-common-database

npm creates the symlink in node_modules and records a file: dependency in package.json, like "flaviocopes-common-database": "file:../flaviocopes-common-database". No global link involved, and the dependency shows up in the lockfile, so anyone who clones the repo sees where the package comes from.

Option 3: workspaces

If the package and the app live in the same repository, put both in an npm workspace. npm links the workspace packages into node_modules for you, without a global npm link.

npm link is still the way to go when the package lives in a separate folder, outside the app repository, and you want changes in it to show up in the app right away.

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: