vy218
vy218

Reputation: 1017

How to specify an npm workspace as a dependency

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]

Upvotes: 13

Views: 18391

Answers (1)

Gianluca Casati
Gianluca Casati

Reputation: 3753

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.

Upvotes: 14

Related Questions