Search code examples
javascriptcssruby-on-railsruby-on-rails-7

CSS and Javascript assets are not reflecting changes on refresh


To keep it simple I'm placing...

  • My CSS styles in app/assets/stylesheets/application.css
  • My javascripts in app/javascript/custom/index.js

To load that javascript I just add <%= javascript_include_tag "custom/index" %&gt; to app/views/layouts/application.html.erb

At the end of rails assets:precompile I have, among other things, this code that the server send to the browser...

<link rel="stylesheet" href="/assets/application-ed7f657c82113ab3654e0f1c0a9fb78eb9439717ba426d64a05914a481e366bf.css" data-turbo-track="reload" />
.
.
.
<script src="/assets/custom/index-a244844108f7509a3d2f83eb57ee786e886c7ebee146c23c1713958fe7d46120.js"></script>

But my real code looks diferent, of course.

So, to see the result of some change into my CSS styles or my javascript code, I have to wait until precompile, reload the page and sometimes event restart the server.

I'm pretty sure that this is not the proper way to work. What would be that proper way? What is the way to write CSS and javascript and prove it easily with Rails 7? What about the images?


Solution

  • Do not precompile in development, run this to remove precompiled assets:

    bin/rails assets:clobber
    

    When you precompile, all your assets are processed and are placed in public/assets directory, these assets do not change automatically and take priority.

    When you don't have a corresponding asset in public/assets, sprockets will locate updated assets in your assets paths (Rails.application.config.assets.paths), it will run any processing that sprockets knows how to do (like minification or compiling .erb assets), and it will serve new and updated assets on the fly when you refresh the page.

    This whole process is very slow, this is why in production we do bin/rails assets:precompile to preprocess assets only once ahead of time.