Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yarn Link All Packages/Workspaces

Yarn's link allows you to register a local package for symlinking into another local package. To use link you cd into the package directory and run yarn link. This works fine on individual packages, however I have a monorepo, using Yarn's workspaces alongside Lerna. There are many packages, and I would like a simple way of linking all the packages within the monorepo.

My package.json:

…
  "workspaces": [
    "packages/*"
  ],
…

My lerna.json:

{
  "npmClient": "yarn",
  "useWorkspaces": true,
  "packages": [
    "packages/*"
  ],
  …
}

Is there a simple way to run yarn link (and yarn unlink) on each package?

like image 610
Undistraction Avatar asked May 16 '26 13:05

Undistraction


2 Answers

Lerna provides the exec command to 'Run an arbitrary command in each package':

link.sh

lerna exec -- yarn link

unlink.sh

lerna exec -- yarn unlink
like image 103
Undistraction Avatar answered May 19 '26 03:05

Undistraction


If I may offer a pure Yarn solution.

Using the Yarn workspace-tools plugin you can make use of the Yarn foreach command to run a command on all workspaces.

To add the plugin run:

yarn plugin import workspace-tools

Usage:

yarn workspaces foreach <commandName> ...

Example:

unlink:

yarn workspaces foreach run unlink

link:

yarn workspaces foreach run link

I would suggest adding 1 command in each workspace with the same name which unlinks and links the required local dependencies then calling them all with one foreach command.

Edited*

After re-reading your inital question I realise you're using Yarn Workspaces which means you don't even need to use Yarn Link at all to have one local package be a dependency in another package.

From the directory of the package which requires the local package run:

yarn add <PACKAGE NAME>@*

Where <PACKAGE NAME> is the name of the required package.

To confirm the dependency was successfully added run:

yarn workspaces info

And confirm your dependency was added it should look like this:

{
  // Rest of the workspace info
  "<DEPENDANT PACKAGE>": {
    "location": "packages/<DEPENDANT PACKAGE>",
    "workspaceDependencies": [
      "<DEPENDENCY PACKAGE>"
    ],
    "mismatchedWorkspaceDependencies": []
  },
}

If your IDE complains about "Cannot find module or its corresponding type declarations" be sure to re-build the package.

like image 45
Lucas L Jordan Avatar answered May 19 '26 01:05

Lucas L Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!