Getting Started With Plug'n'Play
If you use
create-react-app, #5136 (released with the 2.0) implements a
--use-pnpoption that allows you to easily create a new project using PnP! In this case, just use
create-react-app --use-pnptogether with Yarn 1.12, and you're good to go!
Plug'n'Play is a new initiative from Yarn that aims to remove the need for
node_modules. It's already available, and has proved being effective even on large-scale infrastructures. This document describes in a few steps how to quickly get started with it. Spoiler alert: it's quite easy
First, download a package manager that supports it. Yarn 1.12 already does, so that's what we're going to use! To install it, just follow the instructions on our website: https://yarnpkg.com/en/docs/install
If everything is ok, running
yarn --versionshould give you
v1.12.1or higher. If you don't get this result maybe a different Yarn binary is shadowing the one you've just installed - if that happens, just run
which yarnto figure out which binary is being used by your shell.
Once everything is done, choose one of your projects, and
cd into it.
Step 1: Enabling Plug'n'Play
This part is easy! Just run Yarn with the
--pnp flag to enable it:
It will alter your
package.json to include the
installConfig.pnp key, which will indicate to your package manager that you want to use Plug'n'Play if possible (if the package manager doesn't support it, it will just fallback to the regular type of installations - you just won't benefit from the extra safety and improved install time).
And that's it! If everything goes well, you'll see that your
node_modules has disappeared (or that it doesn't seem to contain everything - some tools such as Babel still create some project-specific cache files there):
Step 2: Tooling compatibility
Some tools might require some help to figure out how to use Plug'n'Play. This isn't relevant in most cases because the only packages needing to do this are those that heavily rely on dynamic loading - frontend dependencies typically don't, and as such don't really have this issue. So, what are the packages that need this little outside help?
- Webpack: Just use the plugin pnp-webpack-plugin, and everything will work out of the box
- Rollup: Same as webpack, the rollup-plugin-pnp-resolve plugin transparently adds support PnP
- Jest: Just like the two others, jest-pnp-resolve is the best way to add PnP support
- Typescript: TypeScript is supported if you use Webpack and ts-loader 5.3! Just follow the doc
Note that all the plugins listed above will behave properly regardless of whether you actually use Plug'n'Play or not! Meaning that even if you aren't sure whether all your colleagues will use a package manager supporting Plug'n'Play, you can still rest assured that your project will work for everyone.
Step 3: Enjoy
Once your tools are configured, everything should work fine. If you hit any issue, feel free to open a thread on the Yarn repository, and we'll look into it