linking packages located in monorepos

2020-09-08

 | 

~2 min read

 | 

299 words

Linking packages locally is a tricky thing. It gets even trickier when you want to link a package that’s in a monorepo to another project.

Let’s look at an example. Imagine working in a project that uses ComponentA from monorepo/packages/packageA.

monorepo
.
├── lerna.json
├── package.json
├── packages
│   ├── packageA
│   │   ├── dist
│   │   ├── src
│   │   │   └── ComponentA
│   │   └── package.json
│   ├── ...
│   └── packageZ
│       ├── dist
│       ├── src
│       └── package.json
└── yarn.lock

mainApp imports ComponentA like so:

index.js
import { ComponentA } from "packageA"

But now you want to make changes to ComponentA and link them to mainApp. Traditionally, you would run yarn link from the root of the project you want to make available (in this case that’s monorepo), however because we don’t actually want to link the entire project, but just the subproject, packageA, we need to be more specific in what we link. Other than that, the process is exactly like a normal link1:

createGlobalLink
$ pwd
~/path/to/monorepo
$ cd packages/packageA
$ yarn link
yarn link v1.22.4
success Registered "packageA".
info You can now run `yarn link "packageA"` in the projects where you want to use this package and it will be used instead.
✨  Done in 0.05s.
linkToMainApp
cd ~/path/to/mainApp
yarn link "packageA"
yarn link v1.22.4
success Using linked package for "@olo/design-system-react".
✨  Done in 0.04s.

And that’s it! While the monorepo architecture creates a wrinkle, that’s all it is - a small wrinkle. Once we know how to iron it out, linking works just like normal!

Footnotes

  • 1 While I’ve used yarn in this example, the same principles hold for npm. For more detail, see my post on npm link.


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!