Using a module that’s hosted in npm or on github is fairly easy. You can “npm install” or just update your package.json file with the github location and be done.
But what about developing locally? How do you get your code from a module that you are building, into a project that needs it, without going through the typical npm or github install?
Symlinks To The Rescue
npm has a feature built in to it to help you work on modules locally and use the code in your project without publishing it to the npm repository: symlinks.
The gist of it is that you create a symlink inside of your actual project’s node_modules folder, and you point it to the location of your module on your local system. This lets you run the current, in-development code in your project, without publishing it to npm first.
The best part, though, is that npm automates this for you.
npm link
Say you have a module, “foo”, that you are building on your system. When you have a working version and need to test it in your project, you’ll need to run two steps:
- tell npm this module can be linked
- link it into your project
Start in the “foo” module’s development directory, and run this:
That’s it. Two words: “npm link”.
Behind the scenes, this will tell your local npm installation that the “foo” library can be linked into other projects.
Now head over to the project that needs to use “foo” and run this:
These three words will tell npm to create a link to the “foo” module within the current project.
If you look at the node_modules folder, you’ll see the symlink to the module. This means you can run your standard require(“foo”) call inside of your project, and it will load your local development version of “foo”.
But, what about deployment to production?
Deploying Production Modules
The great thing about linked modules on your local box, is that they are only linked on your local box. The symlink that npm created only exists on your local machine, and nowhere else.
With that in mind, once you have the “foo” module working the way you need it, you would publish it to npm like any other module. Your project’s “package.json” file would still contain a standard reference to the “foo” module, to install from npm, as well.
When you deploy the project and run “npm install” for the production or test or whatever environment, npm will install the published version of your “foo” module.
You only need to make sure you publish the “foo” module before you deploy your code.
Unlinking
P.S. You can just as easily unlink a linked module from your local project with… you guessed it, “npm unlink foo”.