Using yarn/npm link for development

A.Bortnikov

javascriptyarnnpmlinklibrary

frontend, web development

Photo by Daniel von Appen


If you develop library and application that uses it, then you face with problem how to test changes in library on target applications before publishing it. yarn link or npm link where designed to solve this problem.

Here how to use it:

  1. Register link

    1$ cd library
    2$ yarn link
    3yarn link vx.x.x
    4success Registered "library".
    5info You can now run `yarn link "library"` in the projects where you want to use this module and it will be used instead.
  2. Create link

    1$ cd ../application
    2yarn link library
    3yarn link vx.x.x
    4success Registered "library".

    Now there should be symlink application/node_modules/library

    To unlink use yarn unlink library

Development

There are several ways of development library:

  1. Made all necessary changes in library, build it, build application with the changes. Not the best way in terms of time because there might be some things which breaks integration. You will see problems only after all builds (library and application).
  2. Run library and application in dev mode (requires HMR enabled). More efficient method. Webpack and rollup both support HMR with painless setup. Just be sure that library dev mode don't remove files after changes because it will crash target application and full restart will be needed. Appropriate behaviour here is to replace files so there is no moment when application thinks that files are lost.

Note about dependencies

There is confusing thing about yarn link. This command will not install library dependencies (see issue).

At best it will lead build process of application to crash so you immediately see that something is wrong.

At worst you will notice that at very late. Let's say you run application and library in dev mode. You decided to install new dependency to library and everything works on library side but not in application. Even yarn install in application directory won't help. Problem is that application already have new dependency but another version so it crashes not on build process but in some scenarios. In my case I spent hours to figure it out.

So be careful about library dependencies

Conclusion

yarn link or npm link are very useful instruments for library developer but pay more attention when you develop library and applications in parallel.

Contact me: