How to skip automatically running `yarn install` when you precompile

TLDR

Add Rake::Task["yarn:install"].clear to stop Rails from triggering unnecessary runs of yarn install during your deployments.

Background

Do you want to stop seeing extra runs of yarn install when you run rake assets:precompile in your Rails project?

Why are you already running yarn install when you deploy?

  1. If you’re using Docker, yarn install should create a docker image layer, which is a layer prior to the building of assets.
  2. You might be using Heroku’s Node buildpack and that will automatically call yarn install.

Cause

Rails automatically adds a dependency of task yarn:install to assets:precompile in versions prior to 7.x, and some Rails gems add yarn:install as a dependency`. See

In Rails 6.x:

This changed in Rails 7:
Call yarn directly by zarqman · Pull Request #43641 · rails/rails · GitHub so that some Rails gems, notably jsbundling-rails and csbundling-rails now do this dependency enhancement.

SOLUTION to STOP Rails magically calling yarn install

Add this to your project Rakefile, after the call to Rails.application.load_tasks:

# Skip auto-running `yarn install` when running `rails assets:precompile`
Rake::Task["yarn:install"].clear

Shakapacker Issue

If you’re using ShakaPacker, a bug introduced in 6.4.1 is fixed in 6.5.6 per Clean up duplicated yarn install by justin808 · Pull Request #238 · shakacode/shakapacker · GitHub.

1 Like

This is what worked for me:

# in Rakefile
...
Rails.application.load_tasks

if Rake::Task.task_defined?('assets:precompile')
  precompile_task = Rake::Task['assets:precompile']
  precompile_task.prerequisites.delete('webpacker:yarn_install')
  precompile_task.prerequisites.delete('yarn:install')
end