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 | { |
To test this package locally, follow these steps:
Run the command
npm link
. This creates a symbolic link in the/usr/local/lib/node_modules/
folder, which contains globally installed npm packages.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
.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’snode_modules
folder, pointing to the global package.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”]