Projects Blog

Clean install monorepo with Yarn

There are many tools available for managing monorepositories. Some tools serve as dependency management tools, such as npm, pnpm or Yarn, while others function as build systems, like Lerna, Nx or Turborepo.

While there is often flexibility in selecting the preferred tool, I recently encountered a scenario where the choice was more constrained, and I had to select from a limited set of options.

In the context of deploying a project on Vercel, we have several monorepo tools to choose: Nx, Turborepo or Yarn. I opted for the latter.

Why Yarn?

In this situation, I chose this option for the following reasons:

With Yarn, by simply adding a workspaces key in the package.json, I was able to efficiently manage the diverse packages within the project.

What is the problem?

Yarn lacks a straightforward integrated method for re-installing packages, ignoring lock files, while simultaneously cleaning out old or unused installations.

To address this limitation, I have chosen to implement some package JSON scripts. Given my preference for working with npm over yarn, I have ensured that the solution is compatible with both package managers.

The initial step consist on cleaning the locks files: package-lock.json and yarn.lock:

{
"clean:locks": "rm -f package-lock.json && rm -f yarn.lock"
}

Then, and reusing the Shell script explained in the previous article “Remove nested node modules with Shell”, we then proceed to clean each node_modules folder.

{
"clean:node_modules": "find . -name \"node_modules\" -type d -prune -exec rm -rf '{}' +"
}

And now, we want to reinstall. But… you might wonder why we start with yarn and then move on to npm. The reason is that npm provides a method that doesn’t install packages, but creates exclusively the package-lock.json. This makes it more efficient to follow this order for optimal performance.

{
"reinstall": "yarn && npm i --package-lock-only"
}

Finally, we can merge all the scripts into one.

package.json
{
"scripts": {
"reset": "npm run clean:locks && npm run clean:node_modules && npm run reinstall",
"clean:locks": "rm -f package-lock.json && rm -f yarn.lock",
"clean:node_modules": "find . -name \"node_modules\" -type d -prune -exec rm -rf '{}' +",
"reinstall": "yarn && npm i --package-lock-only"
}
}

Keeping our monorepositories controlled is an essential pillar of our architecture.

Fine-tuning project dependencies, crafting semantic scripts, and vigilantly monitoring scalability, contribute to handling big and complex projects.

Happy coding! 🚀

Related posts