NPM Link

Awhile back, I learned how to use npm link. We’ll occasionally use open source packages to get a more complicated component neatly built up. In this particular case, we were working with a component being created by another team in our company that had not yet set up the private hosting. In the meantime, we needed to do some integration testing.

So I download their package to my local machine and follow the steps:

First, in terminal from within the package that I want to “install” using npm link, type the command npm link. In the example below, my package is scoped with the organization name, “@myorg”, so when the link is created, that will be part of the package name.

$ cd my-awesome-package
$ npm link
/usr/local/lib/node_modules/@myorg/my-awesome-package -> /Users/alison/Code/my-awesome-package

Next, navigate into the directory of where you want to install that package.

Then, using the link command with the name of the package (as described in package.json of the package in question, @myorg/my-awesome-package in this example), link it up.

$ cd ../my-fantastic-app
$ npm link @myorg/my-awesome-package
/Users/alison/Code/my-fantastic-app/node_modules/@myorg/my-awesome-package -> /usr/local/lib/node_modules/@myorg/my-awesome-package -> /Users/alison/Code/my-awesome-package

Spin up your app and it should work beautifully!

$ npm start
Module not found: Error: Cannot resolve module '@myorg/my-awesome-package' in /Users/alison/Code/my-fantastic-app/index.js

Only it didn’t.

I double check the link. It’s pointing to the right place. I unlink. I relink. I do all the steps that I can think of. I Google all over, read a bunch of issues on GitHub. None of the suggestions work.

My searching told me that this should be easy. It’s no big deal. It’s one of the simplest things to do.

Finally, I looked at the package.json file of the module I was trying to link to (@myorg/my-awesome-package). I learned that there’s a config setting called main which points to the main file that your module requires.

"name": "@myorg/my-awesome-package",
"version": "0.0.1",
"description": "An awesome package that does cool stuff.",
"main": "build/index.js",
...[more necessary configs]..

Do you see it? The file that my module requires is in a build directory.

I needed to run the build for the package after I downloaded it onto my machine.

Once I did that, it worked like a charm.

The moral of the story is, be sure to follow all appropriate build procedures for any packages, plugins, or libraries that you’re using. Or you might go crazy trying to figure out why such a simple task seems so complicated.

Like what you read? Give Alison Major a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.