I have a monorepo which I'm managing with yarn workspaces + lerna. From what I understand, running yarn
should create a node_modules
directory at the root of the project but not in each individual package. I was following a tutorial where the author says this:
yarn workspaces creates only one node_modules folder. All dependencies are hoisted to the root folder
Is this assumption always true? Or is there a case where yarn + lerna will create individual node_modules
directories in each package?
I read a few articles and was confused with the same thing.
The short answer is, you are right. Yarn creates node_modules
for each package along with a node_modules
directory in the root of your repo.
In other words, Yarn creates /packages/<package>/node_modules
in all your packages. However, the /packages/<package>/node_modules
directory will be optimized by reusing dependencies that are in /node_modules
. This is basically what these authors are trying to say!
To sum it up, you will have n + 1
node_modules
directories, where n
is the number of packages you have, assuming all your packages have dependencies.
Let's consider an example:
yarn workspace package-1 add commander
would not create /packages/package-1/node_modules/commander
if it's already in /node_modules/commander
with compatible versions.
Now let's look at another case:
yarn workspace package-1 add chalk
If Yarn cannot reuse what's in /node_modules
, it will install the package locally, which in our case is /packages/package-1/node_modules/chalk
.
You can read more about this in Yarn's official blog: https://classic.yarnpkg.com/blog/2017/08/02/introducing-workspaces/