How to smoothly develop node modules locally using npm link

So you've found a small piece of code that is a perfect candidate to become a reusable node module. You extract the code into a module, but then begs the question — how can you test the module locally in a project?

JavaScript is all about modules nowadays. With minimal effort you can extract reusable parts of code into modules and share them with the world — or just yourself — using npm.

That's all great, but when developing these modules we want to be able to try them out in our projects — preferably as if the code was in the main project.

Publishing a new version to the npm repository every time you want to test your shiny new lines of code just doesn't cut it.

We need a way to create a seamless dev environment for our modules. Ideally these would also benefit from the awesome hot reloads and watches out there.

This is where npm link saves the day!

Npm link enables us to develop our modules and test them in our projects seamlessly — all locally!

This is done by making our module project look like any other module in the node_modules directory.

npm link does this by creating a symbolic link between the local module and the main project's node_modules.

To see how all this works, say we got a module containing a simple React component that displays a counter.

Making our module available locally

The first step is to make our counter module available locally.

To do this, simply go into the module and run the npm link command.

cd counter  
npm link  
//> /path/to/global/node_modules/counter -> /counter

Great! As you can see, we now got a symbolic link from the global node_modules folder to our module.

Use the local module in our project

Next step is to use the module in a project.

To do that, we first need to go into our main project, then link it to the module using — you guessed right — npm link.

cd main-project  
npm link counter

//> /main-project/node_modules/counter-example -> /path/to/global/node_modules/counter -> /counter

That's it!

We've now created two symbolic links — one from our project to the counter in the global node_modules, which again is a symbolic link to the local module.

So if we now do changes in our counter module and build it, you'll see the change in our main project straight away.

Entering the one-liner

Now that we know how npm link works, let's look at a shorthand that allows us to do the two steps in one go!

So what we need to do is first to go into the project, then run the npm link command together with the path to our module

cd main-project  
npm link ../counter  

Cool, right?

So that's how we can use npm link to create a seamless development experience when developing node modules.

Give it a try and let me know how it works for you!