September 03, 2019
Unless you’re working on a mono-repo, it’s fairly common that in the process of making changes to a code base, you’ll actually need to update the dependency.
When that happens, if you want to test that the changes you’re making work before merging to master in the dependency, linking repos can be a god-send. Enter NPM Link.1
To make this explicit, let’s think about two apps:
AppA is an e-commerce application (could be anything, I just picked e-commerce). We’re building it, and our other apps in React, so
AppB is a shared-UI library full of components that we can re-use across all of different apps.
AppA imports a component, let’s call it
AppB, but it wants some additional validation. Instead of writing that validation in
AppA (and then needing to re-write it in every subsequent app that uses
Input), we want to modify the
Input component directly and then test that the changes took as expected within
AppB(the dependency) in your terminal (or open your text editor’s console)
AppBis written in Typescript), do so now:
npm run build
At this point, any app that has
AppB as a dependency can now link to it. What that means is that when running an app that uses
AppB, instead of using the files in
node_modules, it will reference the local version stored by the link.
AppAin our case
npm link AppBwhere
AppBis the name of the app.
Note: DO NOT run
npm install. That will break the link.
As noted above, the easiest way to break the link is from within
If you’d like a more formal approach, Erin Bush wrote about Linking and Unlinking and has the following steps:2
npm unlink --no-save AppB
If the order is messed up and we unlink
AppA, you can get into a situation where your project,
AppA won’t be able to install its dependency
AppB - linked or not.
The solution (which is hardly a solution) was to remove the local copy and do a fresh copy from the remote repo.
Linking apps is one of my favorite ways to speed up my development. Not only do I not need to wait until my changes to the dependency have been reviewed and merged into master, but I can verify myself that what I want to happen does happen.
While reading up on the topic, in addition to Erin’s post, I found Alexis Hevia’s Medium post quite helpful in understanding how to link and do so safely.3
Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!