Monorepo with npm Workspaces
Intermediate15 minTrending
Set up and manage a monorepo using npm workspaces to share code, dependencies, and scripts across multiple packages in a single repository.
Prerequisites
- -Node.js 16+ and npm 7+ installed
- -Basic package.json knowledge
Steps
1
Initialize the root package
Create the root package.json with workspace definitions.
$ npm init -y && npm pkg set workspaces='["packages/*"]' private=true
The root package must have 'private: true' to prevent accidentally publishing the monorepo root.
2
Create workspace packages
Scaffold individual packages within the workspaces directory.
$ mkdir -p packages/shared packages/api packages/web && npm init -y -w packages/shared && npm init -y -w packages/api && npm init -y -w packages/web
3
Add a dependency to a specific workspace
Install a package into one workspace without affecting others.
$ npm install express -w packages/api && npm install react react-dom -w packages/web
4
Link a workspace as a dependency
Reference one workspace package from another for code sharing.
$ npm install packages/shared -w packages/api && npm install packages/shared -w packages/web
npm automatically creates a symlink. The shared package will appear in the workspace's package.json as a regular dependency.
5
Run scripts across workspaces
Execute npm scripts in specific or all workspaces.
$ npm run build --workspaces && npm run test -w packages/api
Full Script
FAQ
Discussion
Loading comments...