yarn link is a command that allows you to link a local npm package to your current project. Why is that useful? To consume code of a package you usually simply install the package as a dependency to your project. But let's assume you are developing a npm package "my-package" yourself and want to test it within another local project "my-project" first, before publishing it. The solution is to link "my-package" to "my-project".
Another use case could be if you want to check out the source files of a third-party package and use them for debugging in your project.
Change to the root directory of the npm package that you want to make available for linking, e.g. "my-package". Then run:
yarn link --global
This creates a symlink which points to your package in
C:\Users\me\AppData\Local\Yarn\Data\link on Windows or
~/.config/yarn/link in Linux. If you want to specify a different folder you can run the command with this syntax
yarn link --link-folder path/to/dir/
If you get an error such as the following
An unexpected error occurred: "ENOENT: no such file or directory, stat [filename]
then check the "main" or "bin" entry in your
As the success message in the previous step indicates...
success Registered "my-package". info You can now run `yarn link "my-package"` in the projects where you want to use this package and it will be used instead. Done in 0.09s.
you can now change directory to any of your local projects and link "my-package" to it:
cd C:\code\my-project yarn link my-package
Now "my-packge" should appear as a link in the project's
node_modules folder. That also works if your project uses npm instead of yarn.
But here I ran into an error for one of my projects:
Usage Error: Invalid destination; Can't link the project to itself
At first I thought I would have mistakenly run the command in "my-package" instead of my project folder. But that wasn't the case. The actual reason was that I ran the command in a project which was marked as private.
If nothing works you can create a symlink in Windows manually with PowerShell. For example:
New-Item -ItemType SymbolicLink -Path C:\code\my-project\node_modules\@urql\exchange-graphcache -Target C:\code\my-project\urql\exchanges\graphcache
Change directory to your project. The following command will list all dependencies that are linked to your project:
npm ls --depth=0 --link=true
yarn unlink my-package with or without --global in your package.
C:\code\my-package>yarn unlink yarn unlink v1.22.19 success Unregistered "my-package". info You can now run `yarn unlink "my-package"` in the projects where you no longer want to use this package. Done in 0.08s.
After that, run
yarn unlink "my-package" in all projects that have been using it.