/

How to Test an NPM Package Locally

How to Test an NPM Package Locally

If you’re developing your own npm package, it’s important to test it locally before publishing. This is especially useful when you want to modularize your project and reuse specific functionality.

To demonstrate, let’s say I have a package called flaviocopes-common-database. I’ve given it a unique namespace by prefixing it with flaviocopes-. Inside the package directory, I’ve added a package.json file that includes the module name and its dependencies:

1
2
3
4
5
6
7
8
9
10
{
"name": "flaviocopes-common-database",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"pg": "^8.0.2",
"sequelize": "^5.21.6"
}
}

To test this package locally, follow these steps:

  1. Run the command npm link. This creates a symbolic link in the /usr/local/lib/node_modules/ folder, which contains globally installed npm packages.

  2. Now, the local package is accessible globally. You can find it at /usr/local/lib/node_modules/flaviocopes-common-database, pointing to the local file located at /Users/flavio/dev/code/flaviocopes-common-database.

  3. In another project where I want to use this module, I need to execute the command npm link flaviocopes-common-database. This will create a symbolic link in the local project’s node_modules folder, pointing to the global package.

  4. Finally, I can import the module in my Node.js code using the require() syntax:

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

By following these steps, you can easily test and reuse your npm packages locally before publishing them. Happy coding!

tags: [“npm”, “package development”, “local testing”]