rails / sprockets

Rack-based asset packaging system
MIT License
932 stars 792 forks source link

Conditional `link` in manifest.js (assets.precompile discouraged) #784

Open arianf opened 1 year ago

arianf commented 1 year ago

Sometimes, you may want to link certain files only in certain environments. For example, we only want to render the GraphiQL views in our staging and development environment, and not production, or test.

So in our Gemfile we set:

gem 'graphiql-rails', '~> 1.5', group: %I[staging development]

And then we add to our manifest.js :

//= link graphiql/rails/application.css
//= link graphiql/rails/application.js

If we do not add the above, in staging and development, we get the following error:

Asset `graphiql/rails/application.css` was not declared to be precompiled in production.
Declare links to your assets in `app/assets/config/manifest.js`.

  //= link graphiql/rails/application.css

But now that we have added the above, in production and test, we get the following error when trying to precompile assets

$ RAILS_ENV=production bundle exec rake assets:precompile

rake aborted!
Sprockets::FileNotFound: couldn't find file 'graphiql/rails/application.css'
Checked in these paths: 
  /Users/arian/repos/my-app/app/assets/config
  /Users/arian/repos/my-app/app/assets/images
  /Users/arian/repos/my-appi/app/assets/javascripts
  /Users/arian/repos/my-app/app/assets/stylesheets

This was discussed a bit here: https://github.com/rmosolgo/graphiql-rails/issues/13#issuecomment-640366886 and here https://github.com/rmosolgo/graphiql-rails/issues/75#issuecomment-546306742

And here is a suggested solution to the problem: https://github.com/rmosolgo/graphiql-rails/issues/75#issuecomment-555893869

if Rails.env.development? || Rails.env.staging?
  Rails.application.config.assets.precompile += %w[graphiql/rails/application.js graphiql/rails/application.css]
end

But I was under the impression that we should be moving away from the precompile setting. https://github.com/rails/sprockets/blob/070fc01947c111d35bb4c836e9bb71962a8e0595/UPGRADING.md#manifestjs

Existing config.assets.precompile settings will still work for string values (although it is discouraged), but if you were previously using regexp or proc values, they won't work at all with Sprockets 4, and if you try you'll get an exception raised that looks like NoMethodError: undefined method 'start_with?'

Is there a proper way, that is not discouraged to include link conditionally, lets say per environment?

System configuration

Example App (Reproduction) - THIS IS IMPORTANT YOUR ISSUE LIKELY WILL NOT BE RESOLVED WITHOUT THIS

I can add an example app if needed