In this short guide I will explain how to automatically update and fix package vulnerabilities using Yarn. Much like running
npm audit, running
yarn audit returns a list of packages with vulnerabilities. NPM provides a command (
npm audit fix) for automatically upgrading vulnerable packages and fixing the vulnerabilities but there isn't an equivalent command available within Yarn (as of 5th August, 2020).
It's frustrating that yarn doesn't have the equivalent command but the solution, while not ideal, is incredibly simple.
Before you begin modifying your packages, you should ensure that you have version control in place so it's easy to revert any changes if you run into any issues.
To start with you need to generate a package-lock.json by running
npm i --package-lock-only
Once this has been generated you need to delete the existing yarn.lock. Then run
npm audit fix to automatically upgrade and fix security vulnerabilities using NPM. Now we're going to generate a new yarn.lock based on the package-lock.json (which has had the security fixes applied to it) using the yarn import command. To do this simply run
yarn import, which should create our updated yarn.lock file. Finally delete the package-lock.json as we won't be needing it anymore.
This won't always able to automatically fix all dependency vulnerabilities, especially if there isn't a dependency upgrade/fix available. However in one project I was recently able to automatically fix over 1000 dependency vulnerabilities, and in another ~30.
If know what you're doing and you want to copy/paste the commands, all of the commands listed above combined are
npm i --package-lock-only rm -rf yarn.lock npm audit fix yarn import rm -rf package-lock.json
If you found this useful, have any questions, or want more content like this, feel free to follow me on twitter!