kkeri
kkeri

Reputation: 35

How to automatically link npm packages at installation time?

I'm working on a larger project that is split into a number of npm packages. There are several dependencies between the packages. The whole code base is stored in a main directory like this:

main/
  pkg1/
  pkg2/
  ...

Suppose that pkg2 depends on pkg1, so in main/pkg2/package.json I have:

"dependencies": {
  "pkg1": "^0.1.0"
}

I have linked my packages together using npm link. However when I start development on a new machine or for some reason I have to reinstall the packages I can't simply say npm install in pkg2/. It would fail because pkg1 couldn't be found. (It's not published, but anyway, I want the local version because I'm developing both packages).

Of course I can do all the linking manually than call npm install but it's a hassle. Is there any way to do it in a single step?

My previous research:

This question proposes writing a preinstall script, but I don't want to keep linking in production, only in the development environment, as another answer points it out.

I've also tried npm link in pkg1/ then npm install --link in pkg2/. According to the manual,

The --link argument will cause npm to link global installs into the local space in some cases.

Not in my case though.

Upvotes: 1

Views: 1983

Answers (2)

ralphtheninja
ralphtheninja

Reputation: 133118

You can use zelda for this. Written by Feross, it was designed for exactly this purpose.

Upvotes: 1

Paul
Paul

Reputation: 36339

I'm not a fan of doing it this way; I'd generally prefer running a local repository or using git URLs for dependencies like this.

That said, if you want to keep using npm link you can always use the preinstall script approach but not use the preinstall key.

"autolink": "cd ../project1 && npm link && cd ../project2 && npm link project1_name",

Then in your cli you can do $ npm run autolink when you first setup a dev env.

Upvotes: 1

Related Questions