DEV Community

Ravi Katta
Ravi Katta

Posted on • Updated on

How to Add a favicon to the site in Rails 6 using Webpacker

In Rails 6, Adding an icon to the HTML tab is very easy with 3 simple steps.

1) Add an image
2) Reference an image
3) Link an image to HTML head

For the basic understanding on Webpacker, you may refer the useful guide by Chris Oliver (Webpacker Setup)

Here is how our directory structure would look like.

app
 |-controllers
 |-javascript
     |-images
         |-brand_icon.png
         |-brand_icon.ico
     |-packs
          |- application.js
     |-stylesheets 
          |- applicaiton.scss
Enter fullscreen mode Exit fullscreen mode

1) Add an image

The images directory will hold all the images that we link in the project. We can add a types .png, .ico, or .jpeg, but I'd prefer .png as it supports better colors.

Let us save a home image as brand_icon.png to app/javascript/images/*

Brand_icon

2) Reference an image

Declare a constant in packs/application.js file, to refer all the images in javascript/images

 const images = require.context('.../images', true)
Enter fullscreen mode Exit fullscreen mode

Now, with this reference, we can embed all the images in our HTML with a pack tag.

 <%= image_pack_tag 'example.png' %>
Enter fullscreen mode Exit fullscreen mode

3) Link an image to HTML head

Don't forget to link the JavaScript pack in Rails views using the javascript_pack_tag helper.

Now finally, embed the newly downloaded home_icon in HTML view with a helper method favicon_pack_tag.

<!DOCTYPE html>
<html>
  <head>
    <%= javascript_pack_tag 'application', 'data-turbo-links-track': 'reload'%>
    <%= favicon_pack_tag 'brand_icon.png' %>
  </head>
  <body>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

After compiling, the HTML would look like this.

 <link rel="shortcut icon" type="image/x-icon" href="pack/media/images/brand-icon-a3423sf.png">
Enter fullscreen mode Exit fullscreen mode

As we can see the icon is being pointed to the image in the pack directory.

Result

home_tab_icon

That's all we need, CHEERS!!

Top comments (2)

Collapse
 
megatux profile image
Cristian Molina • Edited

I want to add a favicon (ico or png). Don't work here. Error:

Webpacker can't find favicon.png in /home/some_user/code/some_project/public/packs/manifest.json. Possible causes:

  1. You want to set webpacker.yml value of compile to true for your environment unless you are using the webpack -w or the webpack-dev-server.
  2. webpack has not yet re-run to reflect updates.
  3. You have misconfigured Webpacker's config/webpacker.yml file.
  4. Your webpack configuration is not creating a manifest.
Collapse
 
megatux profile image
Cristian Molina

ok, found the error, was using app/assets/images/ and not app/javascript/images/, doh :)