Thursday, December 4, 2014

Testing Local Code Updates made to npm Packages using "npm link"

This article is relevant for: 
- node 0.10.32
- npm 2.1.3
it may or may not work for other versions.

Let's say you have reached the stage in your coding career where you feel the urge to contribute to your favourite open source npm libraries and projects. Maybe you want to fix some bugs or implement some new features and improve these great open source projects.

You would usually start off by cloning or forking your favourite npm project from github, you will then go though the code, work out what it does and fix issues or code in new features. Once you do this, you may wonder "how can I test this change in my your local system?", or "do I need to publish this back into npm and hope it works?".

Ideally, you should be able to switch your local node/npm terminal command that points to the original binary/project to pick up your new changes and then you can use and test it anywhere in your system to see if it works.

For e.g.
1) You love using yuidocs to write documentation for your apps and projects.
2) You have installed yuidocs via the npm package yuidocjs.
3) You have installed it globally in your system.
4) So you can type the command 'yuidoc' in your terminal and it works from anywhere in your file system.
5) But you discover that there is an issue with the yuidoc codebase.
6) You fork the yuidocs project in github, clone it into your local file system and find and fix the issues.
7) NOW, the next time you enter 'yuidoc' in your terminal you want it to pick your updated code so you can test your new updates.

Turns out you can with a very useful npm command that does just this, its called:

npm link

So how do you use it?
1) In point 6 above, once you clone it into your local file system. Open that folder in your Terminal.
2) And then type in "npm link"
3) And thats it... npm now will map the "yuidoc" command to your new codebase.
4) You can now test your changes across your system with your projects using yuidoc and once you are confident that your changes are good, check your code back in and issue a merge request to the upsteam repository requesting they implement you fix.

What if I want to unlink and revert to the original?
There is a "npm unlink" command but it does not seem to work as advertised. I found that the only way to really unlink is to uninstall the original and reinstall that package like so:

// un-install
npm r yuidocjs -g

// re-install
npm install yuidocjs -g

More reading and Resources:

Hope this helps you...

No comments:

Post a Comment

Fork me on GitHub