How to specify an npm workspace as a dependency
Asked Answered
T

1

10

I can’t find the answer to this seemingly obvious question anywhere.

I have some npm workspaces setup in a project. It’s basically a main project with several workspaces within it. They are in a top level folder called “packages”, each in its own folder with its own package.json.

I need to add the workspaces as dependencies of the main project. I’ve added them to package.json of the main project but npm keeps trying to install them from npm.org, and so it fails.

I’m using this syntax:

“workspaces”:[
  “packages/*”
],
“dependencies”: {
  “workspace-a”: “^0.0.1”
  …
}

How do I specify the workspaces as dependencies in package.json?

[Update: the eventual way the main project is used is that it is a dependency of a totally separate project]

Todd answered 4/7, 2022 at 3:19 Comment(3)
AFAIK npm doesn't support glob patterns, try yarn insteadDiscount
Thanks - how about specifying the dependencies, do I use the version number or a local path to the module?Todd
Btw - I got it working using local paths, BUT it only works when running within the main project. The eventual way the main project is used is that it is a dependency of a separate project. When I npm install the separate project it errors saying the workspace projects don’t have a package.json, even though they do. What am I doing incorrectly?Todd
W
9

My solution

I am using explicit workspaces attribute, in the root package.json

  "workspaces": [
    "foo-bar",
    "another-package",
    "path/to/another/workspace"
  ]

Just add the workspace dependency as usual (package name: version). I am opting to use exact version and all my workspace packages has version 0.0.0. So my package json looks like.

  "name": "@project/foo-bar",
  "dependencies": {
    "@project/another-package": "0.0.0"
  },

were @project is the package scope, name it according to your needs.

Differences with widespread solution

Notice that many articles set a wildcard as version, like

  "dependencies": {
    "@project/another-package": "*"
  },

It is also common to see wildcard in workspaces attributes, for example

  "workspaces": [
    "packages/*"
  ]

Motivation

I prefer to avoid wildcards for npm dependency versions.

Using 0.0.0 is valid and if you like this convention it implicitly says that the package is not published on any registry. Furthermore, using this approach can scale well in case you consider to publish some of the internal packages on npm.

I am listing explicitly the workspaces, this is handful cause I have tests that check consistency across workspaces so it is easier to read the workspaces from root package.json and do something with it, rather than open a directory and looking for workspace folders.

Wanwand answered 21/10, 2022 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.