By default yarn installs packages into a “node_modules” directory in the root of the project. Sometimes you might want to install packages to a different directory - we needed to do this for one of our projects and actually a tough time finding documentation on how to do that, so we decided to write this to share what we learned.
The output directory can be changed by running yarn with the command line option --modules-folder
. For example, if you wanted to install packages into a web/vendor
directory instead of node_modules
, you would add the modules-folder option on all yarn commands like yarn install --modules-folder web/vendor
.
It works, but you don’t want to have to include that option EVERY time you want to add a new package, upgrade an existing package, or install updated packages when the lock file changes. Luckily, there’s a way to configure command line options for yarn for a particular project - using the .yarnrc
file.
Create a new file named .yarnrc
in the same directory as your package.json
file. Yarn automatically looks in this file for additional configuration options. Add the command line option to the file like this:
# ./.yarnrc
--modules-folder web/vendor
Now you can run yarn like normal and it will automatically use the web/vendor as the output directory.
Now just run yarn install
and it will install all your packages into web/vendor
instead of node_modules
! Note that yarn will create a node_modules
directory with some files in it which are used by yarn itself - this is expected and shouldn’t cause any issues.
NOTE: There was a bug at some point with yarn where this option would not work if a node_modules
directory already exists in the root of the project. If you run into issues, try deleting the node_modules
directory first if it exists, then run the command.