Yarn workspaces
- React Native course
- Expert
- Lesson 20/47
- 5 min
Learn monorepos with Yarn workspaces.
Yarn workspaces
Yarn workspaces is Yarn's built-in monorepo support. When you add a workspaces field to the root package.json, Yarn hoists all sub-packages' dependencies into one node_modules. This saves disk.
If one sub-package uses another, you link it with "my-utils": "*"; Yarn sets up a symlink. yarn workspaces run build runs build in every package.
One node_modules
Yarn workspaces hoists all dependencies to the root node_modules. Each package does not keep its own; this saves disk and install time.
If a package needs a specific version, it is kept in its own node_modules; if it conflicts with the root version, Yarn uses the local copy. This gives automatic version resolution.
Practice Add a Yarn workspace dependency
In the package.json of an apps/mobile package, add the @my/ui package as a dependency. The version should be "*". Place it under dependencies.
Starter code
{
"name": "@my/mobile",
"version": "1.0.0",
"dependencies": {
"react": "18.2.0"
// Add the @my/ui dependency here
}
}Sample solution
{
"name": "@my/mobile",
"version": "1.0.0",
"dependencies": {
"react": "18.2.0",
"@my/ui": "*"
}
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the Yarn workspaces command
yarn ____ run build
yarn workspaces run build
Explanation: 'yarn workspaces run build' runs in every package.
2 Where does Yarn workspaces collect dependencies?
- In the root node_modules
- Only on GitHub
- Only in the cache
- In each package's own node_modules Correct answer
Explanation: Yarn hoists to the root node_modules.
3 Match the Yarn workspaces pieces
| Term | Meaning |
|---|---|
workspaces field |
In package.json |
hoisting |
Root node_modules |
symlink |
Inter-package link |
yarn workspaces run |
Command in every package |