2019-09-03
|~3 min read
|532 words
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 repositories 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 other apps, in React. As a result, we can benefit from a shared-UI library enabling code reuse across all of our applications. This library will be called LibB
.
AppA
imports a component, let’s call it Input
, from LibB
, 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 AppA
.
LibB
(the dependency) in your terminal (or open your text editor’s console)npm link
LibB
is written in Typescript), do so now: npm run build
At this point, any app that has LibB
as a dependency can now link to it. What that means is that when running an app that uses LibB
, instead of using the files in node_modules
, it will reference the local version stored by the link.
AppA
in our casenpm link LibB
where LibB
is the name of the library’s package.Note: DO NOT run npm install
. That will break the link.
As noted above, the easiest way to break the link is from within AppA
running npm install
.
If you’d like a more formal approach, Erin Bush wrote about Linking and Unlinking and has the following steps:2
AppA
run npm unlink --no-save LibB
LibB
run npm unlink
If the order is messed up and we unlink LibB
before AppA
, you can get into a situation where your project, AppA
won’t be able to install its dependency LibB
- 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
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!