If you’ve recently run yarn install
in a new project, you might be surprised to find that Yarn didn’t generate a node_modules
directory. Instead, you’ll notice a .pnp.cjs
file and a .yarn
directory in your project.
Don’t worry, this is the expected behavior! Yarn has introduced a new package management strategy called Plug’n’Play (PnP) in version 1.12, which eliminates the need for node_modules
.
In this guide, we’ll explore:
- Why Yarn no longer creates a
node_modules
directory - What the
.pnp.cjs
file is - The benefits of using
.pnp.cjs
overnode_modules
- How to enable
node_modules
if you need it for compatibility issues
Let’s dive in 🤿
📹Prefer a video tutorial instead? Treat your ears to my soothing voice ( ͡° ͜ʖ ͡°)
What is Plug’n’Play?
Yarn’s Plug’n’Play is a modern dependency management approach that replaces the traditional node_modules
directory with a more efficient mechanism. Instead of copying dependencies into the project directory, Yarn stores package metadata inside the .pnp.cjs
file and keeps the actual dependencies in a global cache.
Key benefits of Plug’n’Play:
- Since dependencies aren’t copied into every project, installations are much quicker.
- Multiple projects can share the same globally cached dependencies, avoiding unnecessary duplication.
- The
.pnp.cjs
file acts as a dependency map, helping Yarn resolve package locations efficiently without the nested complexity ofnode_modules
. - By using a virtual filesystem, Yarn provides packages without physically placing them inside the project folder.
Overall, PnP optimizes dependency management, making it both faster and more disk space-efficient.
Restoring the node_modules
Directory
While Plug’n’Play offers significant benefits, some projects may encounter compatibility issues with dependencies that rely on the traditional node_modules
structure. If you run into such issues, you can configure Yarn to revert to the old behavior.
To instruct Yarn to create a node_modules
directory, run the following command:
yarn config set nodeLinker node-modules
If the above command doesn’t work as expected, you can manually create the .yarnrc.yml
file at the root of your project and add the following setting:
nodeLinker: node-modules
Conclusion
Yarn’s Plug’n’Play is a powerful alternative to traditional package management, offering improved speed, reduced disk usage, and better dependency resolution. However, in cases where compatibility issues arise, you can easily switch back to using node_modules
.
If you’d like to learn more about Yarn’s Plug’n’Play, check out the official Yarn documentation:
Happy coding đź’ś
Let me know what you think about this article in the comments section below.
If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.