NPM Workspaces: the good, the bad, the ugly, and an overview
As a developer, we have a need to split our code in various packages. This, for a large set of reasons:
- Separate concerns and responsibilities
- The package could be reusable
- Define appropriate tooling chain for the appropriate package
- …
In the NodeJs/NPM ecosystem came a notion of “workspace”: in a mono-repo, we will define various NPM packages defined from a root package rather one.
The main benefits: we regroup a set of logic into the same repository and the versioning/dependencies over packages will be simplified.
This feature was a missing feature for a long time in NPM. That’s why some tooling appeared to deal with this need such as LernaJS, or some NPM alternative evolved to provide it such as Yarn.
Now, we are please to be able to use this feature directly from NPM.
Let’s have a look on it, and let’s discover what will be the good, the bad and the ugly parts. And we will create an example project to illustrate the usage of NPM workspaces.
You will find the source code in the Github repository rochejul/medium-npm-workspaces and each commits reflects the step of the article.
Define your root package
First of all, we have to create a root package (with the usual npm command):
npm initWe will call our project example and provide the right content:
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (example) example
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /xxx/example/package.json:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}
Is this OK? (yes) Our package.json file will be really simple:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}Let’s also run the install command to generate the package-lock.json file:
npm installNow, let’s have a look of the documentation: we have to declare in the package.json file a property called workspaces. This property is an array where you provide a path of folders which contains an NPM package.
You could use globbing to find dynamically the packages. You could have some details with @pnpm/fs.find-packages which reproduces the logic to find programatically the packages of a NPM workspace.
Then your package.json file could be replaced from:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"workspaces": [
"./packages/moduleA",
"./packages/moduleB"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}To:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"workspaces": [
"./packages/*"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}We will also prepare the packages folder:
mkdir packages
touch ./packages/.gitkeepRoot package: public or not public?
What is the purpose of our workspace?
Is it a set of tools like Jest? Then probably the root package should be declared as private and then only packages could be declared as public.
Or is a tool like NPM cli? Then the root package should be declared as public and packages could be also declared as public (and then be used as a reusable part of the tool).
However, we have to be careful of the name of the root package (and of the sub-packages). Indeed, the sub-packages live as “standalone” packages. Meaning there is no notion of naming composition based on the root package: each package should declared his full name.
Usually, the root package has got the name of project and the sub-packages uses some organization name. For example, the root package could be called example and the sub-packages could be named like @example/core.
In our use case, let’s make it private and we will also set the type of the root package as a module:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"description": ""
}And let’s create a simple index.js file:
console.info(`I'm the root package`);Obviously, we are in a NPM project, so we should not forget to provide a .gitattributes and a .gitignore files.
Organize your workspace
Let’s have a deeper look on the npm init command, we could see some options related to workspaces.
And as an overall aspect, most of the npm commands have at least these three workspace parameters:
- workspace: apply the command on one package
- workspaces: apply the command on all packages
- include-workspace-root: apply the command also for the root package (only if we used one of the two previous options)
Obviously, some commands have more (we will see later in the article)
For the init command, workspaces and include-workspace-root are useful only if we have created manually the hierarchy and the package.json files.
In our case, we want to create step by step our workspace, so we will use the workspace option, where we define the name and the path of the new package.
npm init -w ./packages/module-aThis is time to remember the previous section about public/private packages and naming. In our case, the package will be public and their name will start with @example/
package name: (module-a) @example/module-a
version: (1.0.0)
description: The first module
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /xxx/example/packages/module-a/package.json:
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
added 1 package in 24sWe will update the generated package.json file to specify we will use the module type.
Let’s have a look in our workspace:
First, we have only package-lock.json file. In a workspace, we will always one and only one package-lock.json, at the root level.
At this time, we also have one node_modules but if we install dependencies directly on packages with some different versions, we could find multiple node_modules.
Another thing: we could see our created package in node_modules!!
If we look in the package-lock.json, we will understand why:
{
"name": "example",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "example",
"version": "1.0.0",
"license": "ISC",
"workspaces": [
"./packages/*"
]
},
"node_modules/@example/module-a": {
"resolved": "packages/module-a",
"link": true
},
"packages/module-a": {
"version": "1.0.0",
"license": "ISC"
}
}
}The package a symbolic link (behind the hood, the init command used a npm link command). This could be verified with the following command:
ls -la node_modules/@example/module-a
lrwxrwxrwx 1 julien-roche julien-roche 23 Jan 25 15:38 node_modules/@example/module-a -> ../../packages/module-aThe reason? Because we could access our package in the other packages or at the root level. And so import them easily.
Let’s check that. In @example/module-a’s index.js file, we will declare:
export function sum(num1, num2) {
return num1 + num2;
}Let’s create a @example/module-b module and with the following index.js file:
export function sub(num1, num2) {
return num1 - num2;
}Now, at the root package, let’s modify the index.js file in this way:
import { sum } from "@example/module-a";
import { sub } from "@example/module-b";
const result = sub(sum(25, 42), 7);
console.info("Result:", result);And run the script:
npm start
> example@1.0.0 start
> node index.js
Result: 60We are close to have the barebone of our workspace. Indeed, it works because the sub-packages are symboly linked. We have to import them officially in root-package’s package.json.
Let’s achieve this first step by running this command:
npm install --save-exact @example/module-a @example/module-bTada, we have our workspace ready now.
What about package inter-dependencies?
On the previous section, we saw we were able to add at the root-level package as dependencies sub-packages.
This is also possible between packages obviously. We only need on the npm install command to use the workspace option to target the expected package of the workspace.
Here an example:
npm install --save @npmversion/core --workspace=packages/cliThe only rule to respect: the package should be public and so publishable.
Indeed, locally you will never have trouble (though…).
But when an end-user will grab your package A, if it relies to package B of your workspace which is private, it means it cannot be published and so the end-user cannot download it and use your module A.
So what about private packages.
Private packages in my workspace
We have to use a NPM feature called peer dependencies. The main idea: you declare you need a package but the end-user has got the responsibility to install.
However we should be carefull now since NPM v7, we have to also declare a peerDependenciesMeta to really specify this is an optional package (otherwise NPM will do some versioning checkings and so inspect the NPM registry if the package is installed, etc…).
What it involves?
It means private packages are possible in NPM workspaces, but:
- They are not publishable
- They are available only “locally”
- They should be used for tooling aspect
At the end, it means the private packages should be used a devDependencies of your package.
Let’s create a sub-package for testing purpose.
Let’s run the command:
npm init -w ./packages/jest-utilsWe should modify the generated package.json file to specify the package’s type and visibility (private).
We will install some Jest packages:
npm install -w ./packages/jest-utils --save --save-exact jest@29.7.0 @types/jest@29.5.1The package.json file should look
{
"name": "@example/jest-utils",
"version": "1.0.0",
"type": "module",
"private": "true",
"description": "Utility package around jest",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"@types/jest": "29.5.14",
"jest": "29.7.0"
}
}In the index.js file, let’s create a simple matcher (to easily check any kind of object as a plain object):
import { expect } from "@jest/globals";
function plainObject(object) {
return JSON.parse(JSON.stringify(object));
}
expect.extend({
toMatchPlainObject(received, expected) {
const receivedPlainObject = plainObject(received);
const pass = this.equals(receivedPlainObject, expected, [], true);
if (pass) {
return {
message: () =>
`Expected: ${this.utils.printExpected(
expected
)}\nReceived: ${this.utils.printReceived(receivedPlainObject)}`,
pass: true,
};
}
return {
message: () =>
`Expected: ${this.utils.printExpected(
expected
)}\nReceived: ${this.utils.printReceived(
receivedPlainObject
)}\n\n${this.utils.diff(expected, receivedPlainObject)}`,
pass: false,
};
},
});Now let’s use it in the module-a:
npm install -w ./packages/module-a --save-peer --save-exact @example/jest-utilsWe also to declare the peerDependenciesMeta property, and should we have in the package.json of the module-a package:
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"@example/jest-utils": "1.0.0"
},
"peerDependenciesMeta": {
"@example/jest-utils": {
"optional": true
}
}
}To reflect the changes related to peerDependenciesMeta, you should also run a pruning command:
npm pruneCongratulations, you declared a private package in your workspace and use it in another one.
Little disclaimer, we will see on the “Time to bump our version” chapter this is recommended to always use a wildcard rather a strict version:
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"type": "module",
"scripts": {
"dev:linting": "eslint --config=eslint.config.js",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" npx jest --no-cache --config jest.config.json",
"test:coverage": "npm run test -- --coverage"
},
"//": {
"dev:linting": "Lint files",
"test": "Run Jest tests",
"test:coverage": "Run Jest tests and collect coverage"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"@example/jest-utils": "*"
},
"peerDependenciesMeta": {
"@example/jest-utils": {
"optional": true
}
}
}Let’s run some tests (and some other commands)
On a NPM project, we usually use npm run-script to have some commands for the dev tool chain (running tests, styling, generate docs, etc…) and we also use it for a CI perspective.
Let’s enable some tests and see how it works with a NPM workspace.
Get Julien Roche’s stories in your inbox
Join Medium for free to get updates from this writer.
In the module-a package, we will create the jest.config.json file:
{
"clearMocks": true,
"collectCoverage": true,
"collectCoverageFrom": ["index.js"],
"coverageThreshold": {
"global": {
"lines": 90,
"statements": 90
}
},
"coverageDirectory": "<rootDir>/coverage",
"moduleFileExtensions": ["mjs", "js"],
"setupFilesAfterEnv": ["<rootDir>/test/jest.setup.js"],
"testEnvironment": "node",
"testRegex": [".*test\\.js$"],
"transform": {},
"verbose": true
}We prepare the test npm run-script in module-a’s package.json file (NB: we use the module type for our package, so we have to declare some flags for Jest):
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"type": "module",
"scripts": {
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" npx jest --no-cache --config jest.config.json",
"test:coverage": "npm run test -- --coverage"
},
"//": {
"test": "Run Jest tests",
"test:coverage": "Run Jest tests and collect coverage"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"@example/jest-utils": "1.0.0"
},
"peerDependenciesMeta": {
"@example/jest-utils": {
"optional": true
}
}
}And create a very very very basic test (where we use the custom matcher toMatchPlainObject we created in the private package jest-utils):
import { describe, test, expect } from "@jest/globals";
import "@example/jest-utils";
import { sum } from "../index.js";
describe("@example/module-a - sum", () => {
test("we should sum the two parameters", () => {
// Arrange
const leftOperand = 25;
const righOperand = 37;
const expected = { sum: 62 };
// Act
const actual = sum(leftOperand, righOperand);
// Assert
expect({ sum: actual }).toMatchPlainObject(expected);
});
});If we run the following commands:
cd ./packages/module-a
npm testWe will have as output:
> @example/module-a@1.0.0 test
> NODE_OPTIONS="$NODE_OPTIONS --enable-source-maps --experimental-vm-modules" npx jest --no-cache --config jest.config.json
(node:6185) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
PASS test/index.test.js
@example/module-a - sum
✓ we should sum the two parameters (3 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.64 s
Ran all test suites.So the test works fine and it proves the imported private package works too. But we needed to execute the command within the package scope.
How to run it from the root-level package?
We need to use the workspace option. If we adapt the root-level package.json file:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"start": "node index.js",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
}
}Then:
~/dev/github/example$ npm run test:module-a
> example@1.0.0 test:module-a
> npm test --workspace=./packages/module-a
> @example/module-a@1.0.0 test
> NODE_OPTIONS="$NODE_OPTIONS --enable-source-maps --experimental-vm-modules" npx jest --no-cache --config jest.config.json
(node:6509) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
PASS test/index.test.js
@example/module-a - sum
✓ we should sum the two parameters (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.628 s
Ran all test suites.Great, but let’s see to generalize it with one command for all packages with the option workspaces:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"start": "node index.js",
"test": "npm run test --workspaces",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"test": "Run tests for all sub-packages",
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
}
}If we run the command, we could see a failure:
~/dev/github/example$ npm test
> example@1.0.0 test
> npm run test --workspaces
npm error Lifecycle script `test` failed with error:
npm error Error: Missing script: "test"
To see a list of scripts, run:
npm run
npm error in workspace: @example/jest-utils@1.0.0
npm error at location: /xxx/dev/github/example/packages/jest-utils
> @example/module-a@1.0.0 test
> NODE_OPTIONS="$NODE_OPTIONS --enable-source-maps --experimental-vm-modules" npx jest --no-cache --config jest.config.json
(node:7486) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
PASS test/index.test.js
@example/module-a - sum
✓ we should sum the two parameters (3 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.704 s
Ran all test suites.
npm error Lifecycle script `test` failed with error:
npm error Error: Missing script: "test"
To see a list of scripts, run:
npm run
npm error in workspace: @example/module-b@1.0.0
npm error at location: /xxx/dev/github/example/packages/module-bThis is logic: we never declare any tests yet in module-b. Hopefully, we could use the if-present option which ignore packages where the command is not declared:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"start": "node index.js",
"test": "npm run test --workspaces --if-present",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"test": "Run tests for all sub-packages",
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
}
}Then, the npm test command works fine:
~/dev/github/example$ npm test
> example@1.0.0 test
> npm run test --workspaces --if-present
> @example/module-a@1.0.0 test
> NODE_OPTIONS="$NODE_OPTIONS --enable-source-maps --experimental-vm-modules" npx jest --no-cache --config jest.config.json
(node:7244) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
PASS test/index.test.js
@example/module-a - sum
✓ we should sum the two parameters (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.658 s
Ran all test suites.We could see we executed the test commands only in sub-packages. If we want to execute it also on the root-level, we could use the include-workspace-root option, but in our case, we shouldn’t otherwise we will have an infinite loop -_-’.
What about publishing our packages?
We have to use the npm publish command. Similarly, we could use the various workspaces options and we could have a command such as:
npm publish --workspaces --include-workspace-rootThe above commands:
- Will try to publish any sub-packages (if this is specified as private, the package will be ignored)
- Will try to publish the root level package (if this is specified as private, the package will be ignored)
At the end, this part of the journey is really a sample one and the root-level package.json file looks like now:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"dev:publish": "npm publish --workspaces --include-workspace-root",
"start": "node index.js",
"test": "npm run test --workspaces --if-present",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"dev:publish": "Publish all the packages on npm registry",
"test": "Run tests for all sub-packages",
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
}
}Nota Bene: on the first time, ensure you have declare the organization @example in your NPM profile with this link:
Then you will find in your NPM profile the newly declared profile and see next the published packages:
Vscode integration (with Jest, Eslint, etc…)
I usually code with VsCode for years now. And then I used the Jest plugin and Jest-Runner plugin. For NPM workspaces, we will see we have to adjust the configurations.
First all, at the root-level, under .vscode folder, let’s an usual settings.json file:
{
"jest.jestCommandLine": "npx jest --no-cache",
"jest.nodeEnv": {
"NODE_OPTIONS": "--experimental-vm-modules"
},
"jest.runMode": "on-save",
"jest.debugMode": true,
"jest.coverageFormatter": "DefaultFormatter",
"jest.coverageColors": {
"covered": "rgba(9, 156, 65, 0.4)",
"uncovered": "rgba(255,99,71, 0.2)",
"partially-covered": "rgba(255,215,0, 0.2)"
},
"jestrunner.jestCommand": "NODE_OPTIONS=\"--experimental-vm-modules\" npx jest",
"jestrunner.runOptions": ["--no-cache", "--coverage=false"],
"jestrunner.debugOptions": {
"env": { "NODE_OPTIONS": "--experimental-vm-modules" },
"args": [
"--runInBand",
"--no-cache",
"--coverage=false",
"--colors",
"--verbose",
"--watchAll=false"
]
}
}Within VsCode, when we run the tests with the run action or when we modify a test, the tests will be executed successfully:
However for testing tab, when we will have set the tests for all packages, everything will be mixed and executed at the same time.
To organize the testing tab, we could use the jest.virtualFolders to help the plugin to structure the tests:
{
"jest.jestCommandLine": "npx jest --no-cache",
"jest.nodeEnv": {
"NODE_OPTIONS": "--experimental-vm-modules"
},
"jest.runMode": "on-save",
"jest.debugMode": true,
"jest.coverageFormatter": "DefaultFormatter",
"jest.coverageColors": {
"covered": "rgba(9, 156, 65, 0.4)",
"uncovered": "rgba(255,99,71, 0.2)",
"partially-covered": "rgba(255,215,0, 0.2)"
},
"jest.virtualFolders": [
{ "name": "module-a", "rootPath": "packages/module-a" }
],
"jestrunner.jestCommand": "NODE_OPTIONS=\"--experimental-vm-modules\" npx jest",
"jestrunner.runOptions": ["--no-cache", "--coverage=false"],
"jestrunner.debugOptions": {
"env": { "NODE_OPTIONS": "--experimental-vm-modules" },
"args": [
"--runInBand",
"--no-cache",
"--coverage=false",
"--colors",
"--verbose",
"--watchAll=false"
]
}
}Another important aspect: at this time it executes in the same way the packages. But for some packages, we could have specificities (maybe we need more Jest plugins, a specific configuration, we don’t use the module type, etc…).
Then VsCode allows in each package to create our own .vscode folder and then another settings.json to override only what we want to override:
{
"jest.jestCommandLine": "npx jest --no-cache --config ./jest.config.json",
"jestrunner.configPath": "./jest.config.json"
}We will have some troubles with Eslint. The VsCode’s plugin for Eslint works by default as everything is at the root level. We need then to declare on each folder level (and so packages) to check there isn’t some configuration.
It means then we could tune Eslint for each packages depending of the scope of the package (NodeJS only? Web? etc…):
{
"eslint.workingDirectories": [{ "mode": "location" }],
"eslint.useFlatConfig": true,
"jest.jestCommandLine": "npx jest --no-cache",
"jest.nodeEnv": {
"NODE_OPTIONS": "--experimental-vm-modules"
},
"jest.runMode": "on-save",
"jest.debugMode": true,
"jest.coverageFormatter": "DefaultFormatter",
"jest.coverageColors": {
"covered": "rgba(9, 156, 65, 0.4)",
"uncovered": "rgba(255,99,71, 0.2)",
"partially-covered": "rgba(255,215,0, 0.2)"
},
"jest.virtualFolders": [
{ "name": "module-a", "rootPath": "packages/module-a" }
],
"jestrunner.jestCommand": "NODE_OPTIONS=\"--experimental-vm-modules\" npx jest",
"jestrunner.runOptions": ["--no-cache", "--coverage=false"],
"jestrunner.debugOptions": {
"env": { "NODE_OPTIONS": "--experimental-vm-modules" },
"args": [
"--runInBand",
"--no-cache",
"--coverage=false",
"--colors",
"--verbose",
"--watchAll=false"
]
}
}Volta usage
VoltaJs is a JavaScript Tool Manager: it will download any version of what you want of NPM, NodeJs, Yarn, etc…
And then it will setup your shell to use the appropriate version, regardless where you are on your file system (e.g. if you have two projects and you setup different versions of NPM for example, when you navigate through your shell, the version of NPM will be setted automatically).
This is pretty helpfull when you have mutliple team mate on the same project or simply if someone want to fork your project, he will be able to use the appropriate set of tools.
Let’s run the following command on the root-level package:
~/dev/github/example$ node --version && npm --version
v22.13.1
10.9.2As you can see, the latest version NodeJs (at this time) is installed. However we want to use node@20.x instead. Let’s update our package.json like so:
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"dev:linting": "npm run dev:linting --workspaces --if-present",
"dev:publish": "npm publish --workspaces --include-workspace-root",
"start": "node index.js",
"test": "npm run test --workspaces --if-present",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"dev:linting": "Lint files over packages",
"dev:publish": "Publish all the packages on npm registry",
"test": "Run tests for all sub-packages",
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
},
"devDependencies": {
"eslint": "9.16.0",
"eslint-plugin-jest": "28.9.0"
},
"volta": {
"node": "20.15.0",
"npm": "10.7.0"
}
}Then, if we type the above command line:
~/dev/github/example$ node --version && npm --version
v20.15.0
10.7.0Let’s take the opportunity to define the expected engine for our project (this is a pretty common usage to 1) inform the developers of the compatible version of your project 2) inform the consumer if he could use the project):
{
"name": "example",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"private": "true",
"workspaces": [
"./packages/*"
],
"scripts": {
"dev:linting": "npm run dev:linting --workspaces --if-present",
"dev:publish": "npm publish --workspaces --include-workspace-root",
"start": "node index.js",
"test": "npm run test --workspaces --if-present",
"test:module-a": "npm test --workspace=./packages/module-a"
},
"//": {
"dev:linting": "Lint files over packages",
"dev:publish": "Publish all the packages on npm registry",
"test": "Run tests for all sub-packages",
"test:module-a": "Run tests only for @example/module-a"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@example/module-a": "1.0.0",
"@example/module-b": "1.0.0"
},
"devDependencies": {
"eslint": "9.16.0",
"eslint-plugin-jest": "28.9.0"
},
"engines": {
"node": "^16.10.0 || ^18.12.0 || >=20.0.0"
},
"volta": {
"node": "20.15.0",
"npm": "10.7.0"
}
}Great.
Wait, what about the sub-packages:
If we run:
~/dev/github/example$ cd ./packages/module-a
~/dev/github/example/packages/module-a$ node --version && npm --version
v22.13.1
10.9.2We could see we use the default NodeJs version of the system.
We have two solutions:
- Duplicate the configuration :’(
- Use the VoltaJs’ extends capability
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"type": "module",
"scripts": {
"dev:linting": "eslint --config=eslint.config.js",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" npx jest --no-cache --config jest.config.json",
"test:coverage": "npm run test -- --coverage"
},
"//": {
"dev:linting": "Lint files",
"test": "Run Jest tests",
"test:coverage": "Run Jest tests and collect coverage"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"@example/jest-utils": "1.0.0"
},
"peerDependenciesMeta": {
"@example/jest-utils": {
"optional": true
}
},
"engines": {
"node": "^16.10.0 || ^18.12.0 || >=20.0.0"
},
"volta": {
"extends": "../../package.json"
}
}Then, when we type again the above command:
~/dev/github/example$ cd ./packages/module-a
~/dev/github/example/packages/module-a$ node --version && npm --version
v20.15.0
10.7.0Everything is fine! And if needed, we could adapt the version depending of our package.
The only sad aspect: NPM doesn’t have package.json inheritance. Meaning we have to duplicate the engines section for each sub-packages.
Time to bump our version
Let’s go from version 1.0.0 to 1.1.0.
We will use the npm version command on that perspective, and we will raise at the root-level package:
npm version minor --no-git-tag-version --allow-same-versionno-git-tag-version is used to prevent to create a git tag and allow-same-version is used if we manually provide the version and this is the same (here he should not be the case as we request to upgrade the version based on the minor’ semver semantic.
If we run the command, we will have:
Only the root-level’s package.json was updated. Hopefully, we have the workspaces and include-workspace-root options. If we revert the changes and we run:
npm version minor --no-git-tag-version --allow-same-version --workspaces --include-workspace-rootAll the files will be updated:
But we will have this error:
example
v1.1.0
@example/jest-utils
v1.1.0
@example/module-a
v1.1.0
@example/module-b
v1.1.0
npm warn ERESOLVE overriding peer dependency
npm warn While resolving: @example/module-a@1.1.0
npm warn Found: @example/jest-utils@undefined
npm warn node_modules/@example/jest-utils
npm warn workspace packages/jest-utils from the root project
npm warn
npm warn Could not resolve dependency:
npm warn peerOptional @example/jest-utils@"1.0.0" from @example/module-a@1.1.0
npm warn packages/module-a
npm warn @example/module-a@1.0.0
npm warn node_modules/@example/module-a
npm error code E404
npm error 404 Not Found - GET https://registry.npmjs.org/@example%2fjest-utils - Not found
npm error 404
npm error 404 '@example/jest-utils@1.0.0' is not in this registry.
npm error 404
npm error 404 Note that you can also install from a
npm error 404 tarball, folder, http url, or git url.
npm error A complete log of this run can be found in: /home/julien-roche/.npm/_logs/2025-02-02T12_53_05_221Z-debug-0.logThis is logic: @example/jest-utils is a private package and we set the version to 1.0.0 in @example/module-a. As the package was updated, as as the npm version command runs a pruning command at the end, it will access everything is correct. Then it breaks the symbolic link because no @example/jest-utils@1.0.0 is present locally and then will try to download it.
That’s why we should always declare a private dependency usage with a wildcard instead:
{
"name": "@example/module-a",
"version": "1.0.0",
"description": "The first module",
"main": "index.js",
"type": "module",
"scripts": {
"dev:linting": "eslint --config=eslint.config.js",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" npx jest --no-cache --config jest.config.json",
"test:coverage": "npm run test -- --coverage"
},
"//": {
"dev:linting": "Lint files",
"test": "Run Jest tests",
"test:coverage": "Run Jest tests and collect coverage"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"@example/jest-utils": "*"
},
"peerDependenciesMeta": {
"@example/jest-utils": {
"optional": true
}
},
"engines": {
"node": "^16.10.0 || ^18.12.0 || >=20.0.0"
},
"volta": {
"extends": "../../package.json"
}
}Run a pruning command, create a git commit.
If we rerun the above npm version command, we will have then:
~/dev/github/example$ npm version minor --no-git-tag-version --allow-same-version --workspaces --include-workspace-root
example
v1.1.0
@example/jest-utils
v1.1.0
@example/module-a
v1.1.0
@example/module-b
v1.1.0
up to date in 1s
57 packages are looking for funding
run `npm fund` for detailsAt the first glance, it seems fine.
But if we look closely, we will see the inter-dependencies are not updated. and we still use the 1.0.0 version:
It seems to be intended and we have to manually change the versions and run the pruning command.
This is a debate.
In my point of view, we use a mono-repo. And the npm version command enforces to create a git tag (this is enabled by default). And as we have a mono-repo, we couldn’t update independently the packages of the workspaces and then have a git tag for each packages… except if we don’t have a mono-repo -_-’.
In this example, we will do it manually.
But you could create a script to automate it if you want.
I recommend the usage of @npmcli/package-json module.
This is a module used within NPM and it updates the package.json files in the same way as NPM commands (this is logic as this used by default).
Why no usage of npm install commands? Because we will face to a looooooooot of troubles >_<.
If we run the following after the global bumping (if we used module-b as a dependency of module-a):
npm install --save @example-b@1.1.0 -w ./packages/module-aSometimes, it will work. Sometimes not…
So we will use the force option:
npm install --save @example-b@1.1.0 -w ./packages/module-a --forceSometimes, it will work. Sometimes not… Again!!
We will have some weird error:
npm ERR! Cannot set properties of null (setting 'dev')And this error seems to be known… and sometimes it appears, sometimes it disappears…
IMO, I recommend to modify the package.json files manually or with a script. For a tool I made, I create a package for this perspective: @npmversion/workspace.
Conclusion
This is really really to see we could organize our packages within a mono-repo.
With some basics commands, we could create the hierarchy, create inter-dependencies, quickly. In my sense, the only trick is about the private packages.
Some configuration is required for our IDE, and also for some tools but no real blockers.
In my sense, the main troubles came with the bumping part. And it was painful to find a safe path.
Of course, some nice features could be possible, like package.json inheritance (I know Yarn allows this feature). But I prefer to use the Vanilla approach and then embrace the tools capabilities of NodeJs.
But now I’m happy to use NPM workspaces.






