npm workspaces
- React Native course
- Expert
- Lesson 21/47
- 5 min
Learn monorepos with npm workspaces.
npm workspaces
npm workspaces is npm 7+'s built-in monorepo support. It is similar to Yarn workspaces; you add a workspaces field to the root package.json. npm install sets up all packages in one command.
Commands: npm run build --workspaces (build in all packages), npm install <pkg> -w apps/mobile (add a dependency to a specific package). A symlink is set up like in Yarn.
Yarn vs npm
Yarn and npm workspaces are similar concepts; both use workspaces in the root package.json. Differences: Yarn uses yarn workspaces run, npm uses the --workspaces flag. Plug-and-play (PnP) is Yarn-only.
The choice depends on team habit. Speed benchmarks keep changing; both are actively developed. What matters is consistency: do not mix them in one project.
Practice Add an npm workspaces script
Add a scripts field to a root package.json. It should contain "build": "npm run build --workspaces".
Starter code
{
"name": "my-monorepo",
"private": true,
"workspaces": ["apps/*", "packages/*"]
// Add the scripts field here
}Sample solution
{
"name": "my-monorepo",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"build": "npm run build --workspaces"
}
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the npm workspaces commands
| Term | Meaning |
|---|---|
npm install |
Installs deps |
--workspaces |
All packages |
-w apps/mobile |
Single package |
npm run build |
Runs build |
2 From which npm version is npm workspaces built in?
- Only npm 1 Correct answer
- Only npm 3
- npm 7 and later
- No version
Explanation: npm workspaces came with npm 7.
3 Write the package path for the dependency add
npm install lodash -w ____
npm install lodash -w apps/mobile
Explanation: -w apps/mobile adds to a single package.