Npm

Npm link

npm link command

The problem

Imagine you create have a library. You add new feature / change something inside your library. Your tests pass. You feel right about the change. Everything seems good. But you can’t check it for real if you don’t run npm publish to publish a new version to the npm registry. No worries - npm link to rescue!

Npm link

npm link symlink a package folder (creates a symbolic link to a package folder) during development. Meaning that you can tell npm (or yarn) to resolve a specific package from a local path instead of the npm registry. It’s useful if you want to update the library source code and check its integration with other packages, or use the library it in another project while it’s still in active development.

I use it when I created my eslint-plugin-sort-export-all. At first, I pushed my code to npm after my test passed. Then I install the package from npm and only after then I could see the effect in my IDE. like a real user. But then, as I created small changes frequently (change ESLint rule report message) and I felt it isn’t productive. Every time I wanted to change the library code - I have to push -> publish -> install. Npm link helps me to shorten this loop.

Usage

  1. Go to your library code root (where you would like to link) and run:

    cd library-name-path
    npm link

    It creates a smylink in the global folder {prefix}/lib/node_modules/library-name that links to the package

  2. Go to your project (where you consume the library) and run

    cd project-name-path
    <!-- Note that library-name is taken from package.json, not from directory name. -->
    npm link library-name

    This will create a smylink named from globally installed package-name to node_modules/ of this current folder.

    you can also run npm unlink to unlink.

For more details see npm docs or yarn docs.

Conclusion

Following those steps - I could change my library code during development, and check it’s integration as it publishes to npm (without publishing it). This helps me be more productive. Next time you use code that sits in a different package you want to test a change in this package in my App during development - use npm link.

Looking forward (where npm link is not enough)

Before I published this article I notice another tool that aims to solve the same problem, in cases that npm link is not good enough. see yalc

Subscribe to Nir Tamir

Get the latest posts delivered right to your inbox