Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node workspaces — require local package

I am using the workspaces feature of node/npm and the layout is like that:

.
+-- package.json
`-- packages
   `-- p1
      `-- package.json
   `-- p2
      `-- package.json
./package.json

{
  …
  "workspaces": [
    "./packages/*"
  ],
  …
  "dependcies": { … }
  …
}

npm install and everything is working to far. But now I would like to add the package p1 as dependency to package p2. But how do I have to do that? Naively I have tried that:

./packages/p2/package.json

{
  …
  "dependencies": {
    "p1": "*"
  }
  …
}

But that yields an error on install, telling me that p1 cannot be found the registry.

like image 585
philipp Avatar asked Dec 17 '25 13:12

philipp


2 Answers

UPDATE - using npm cli
From the project root directory run

npm i ./packages/p1 -w packages/p2

The ./ is a MUST or else npm will confuse the install as a package install from npm registry vs from a local directory.

Manual Workaround
Manually add p1 as a local dependency by providing p1's relative path in p2 package.json, so in your example:

./packages/p2/package.json

{
  …
  "dependencies": {
    "p1": "file:../p1"
  }
  …
}

Then you'll need to run npm install in the p2 package.

I found that solution from a LinkedIn article Things I wish I had known when I started JavaScript monorepo with Lerna.

like image 145
Klynton Avatar answered Dec 19 '25 07:12

Klynton


.
+-- package.json
`-- packages
   `-- p1
      `-- package.json
   `-- p2
      `-- package.json

With NPM workspaces, do not specify your dependency to p1 in ./packages/p2/package.json.

NPM will figure out your local dependencies automatically.

if your specify p1 in your dependencies, it will install an outdated version under your projects P2 node_modules. To fix this when that happens:

  1. Delete that old version of P1 under the node_modules of P2
  2. Remove the P1 dependency in ./packages/p2/package.json.
  3. Rebuild everything.

Wish they explained this better in the docs: docs.npmjs.com/cli/v9/using-npm/workspaces?v=true

like image 20
Stephane Avatar answered Dec 19 '25 06:12

Stephane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!