You no longer need to use yarn in Rails projects

19.02.2024 - Andy Pfister

With the introduction of the webpacker gem in Rails 6.0, Rails chose yarn as the package manager for Node. Yarn was generally faster than NPM at the time due to using parallel downloads, so the choice made sense. However, NPM has caught up over the years, and newer JavaScript projects are generally created with NPM now. But Rails kept their hard-coded dependency on yarn until recently.

Starting with jsbundling-rails v1.2.2 and cssbundling-rails v1.4.0, different package managers other than yarn are supported. Both gems use a simple algorithm probing files and commands to determine which package manager should be used:

def tool
  when File.exist?('bun.lockb') then :bun
  when File.exist?('yarn.lock') then :yarn
  when File.exist?('pnpm-lock.yaml') then :pnpm
  when File.exist?('package-lock.json') then :npm
  when tool_exists?('bun') then :bun
  when tool_exists?('yarn') then :yarn
  when tool_exists?('pnpm') then :pnpm
  when tool_exists?('npm') then :npm

As you can see, your choices are Bun, Yarn, PNPM, and NPM.

We are moving our projects to NPM since it makes the setup of an application easier if you do not need an additional package manager. Bun also looks promising but requires extra steps for migration.

Switching from yarn to NPM is simple:

  1. Delete the yarn.lock file
  2. Run npm install.
  3. Check your code base for commands that invoke yarn and replace them with npm.

For example, you might have a to run the Rails server and the JS / CSS build process simultaneously. Or you have a CI script where you run yarn install.

Rails also generates a yarn file in the bin folder. We usually delete it instead of adapting it to invoke npm, as there is not much value added by this script.

That’s all to it! Switching from yarn to NPM should simplify your setup while not losing out on performance anymore.