Using npm link to use node modules that are "in progress"

Share this video with your friends

Social Share Links

Send Tweet

It is some times convenient, even necessary, to make use of a module that you are working on before it has been published to the node package manager (npm). The npm link command makes this simple.

[00:00] Sometimes you need to use a module before it has been published, or before you are ready to publish a new version of it. NPM provides a command called "link" which is useful for exactly that purpose. In this case, we have this module named "upper" which has the amazing functionality of taking in a string and returning the uppercase version of it. That's located here in this upper directory, and we want to use it from this user directory.

[00:29] Our index file and user just requires upper, and then logs out, passing the string "Hello World" to it. We're in the user directory here, so if we try and use this, we're going to get this error that says, "Cannot find module 'upper.'" That's because we haven't installed it. In fact, we really can't install it because upper hasn't been published anywhere.

[00:54] But there's a way around this, and that is to go over to the upper directory and then say, "npm link," and npm link you can see is going to create a symbolic link in user/local/lib/node modules/upper to that directory that we were just in. We've now created that sym link in our system, so if we go back into the user directory, we now have to basically tell it we want it to use this location.

[01:30] We're going to say, "npm link upper," and you can see it's going to then create a three-step symbolic link. It's going to link the node modules/upper directory within our user directory to that place that we created the symbolic link in the last step, which then of course points to Upper itself. Now we can actually run our index file that uses Upper, and we see that output of "Hello World."

[02:05] One thing to note, especially if you're on a Mac, is that when you're done needing this, your module has been published, or you're just done with this project, whatever the case may be, you should unlink this module, because it can cause problems with things like Time Machine that it's sort of hard to track down. If we then just say, "npm unlink upper," you'll see that it unbuilds that reference, and now if we run our program again, we're going to get that error again.

[02:40] Use npm link with no arguments in the module directory that you want to provide to other modules, and then npm link with that module name where you want to use it. One thing to note is that the npm link command does require that you have the package.json file, because it's going to actually use the name field from there to create that reference.