3

I would like to inline some CSS within my html. I have done this in the past with Sprockets putting something like that in my layouts/application.html.erb

<style>      
  <%= Rails.application.assets["application.css"].to_s.html_safe %>
</style>

Now I would like to do the same but with CSS assets bundled by Webpacker.

I am able to get the path of the file with Webpacker.manifest.lookup("application.css"), but I am missing the latest part to get the content and embed it into the layout

The rationale behind this:

To improve page speed I want to embed my critical CSS into the header of the HTML. Using Webpack and PostCss tools (PurgeCss). I am able to get a very compact very of my CSS for the above the fold of my home page.

The rest of the CSS is loading asynchronously with the usual packs helpers

Update 1

Here is the link to the article I wrote thanks to the answer.

https://dev.to/adrienpoly/critical-css-with-rails-and-webpacker-sprocketsless-part-1-2bck

3
  • Maybe you want to add to the question why you need to include an asset that way. Commented Aug 26, 2019 at 19:34
  • sure, just added some rationale behind this Commented Aug 26, 2019 at 19:54
  • Rails.application.assets is nil in production. This is by design. Commented Aug 29, 2019 at 6:48

1 Answer 1

6

Let's consider having a line in app/javascript/packs/application.js

import `../css/application.css'

and a file app/javascript/css/application.css with some useful content.

Then you spell

<style>
  <%= File.read(File.join(Rails.root, 'public', Webpacker.manifest.lookup('application.css'))).html_safe %>
</style>

and it simply works.

Don't forget:

  1. To set extract_css: true in config/webpacker.yml
  2. Exec rake webpacker:compile after changing these .css and/or .js files. Or use webpack-dev-server for a things like Hot Module Replacement
  3. Turn on (though this is default setting for development) config.public_file_server.enabled = true (as @Adrien mentioned in comments) for serving .js resources by puma
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks this is exactly what I was looking for. Works like a charm.
sorry my bad actually after restarting the server I am getting a No such file or directory @ rb_sysopen error
Which environment do you use? Is there /public/packs/application.css file under app's root? Is there extract_css option in the config/webpacker.yml?
I am in development mode. I do have extract_css: true in my webpacker.yml config
If I add in a normal way my pack then in my html it is fetched from /public/packs/application-[hash-id].css but this is in development so I don't see it in real in my public folder
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.