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
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/*
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)
Now, with this reference, we can embed all the images in our HTML with a pack tag.
<%= image_pack_tag 'example.png' %>
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>
After compiling, the HTML would look like this.
<link rel="shortcut icon" type="image/x-icon" href="pack/media/images/brand-icon-a3423sf.png">
As we can see the icon is being pointed to the image in the pack directory.
Result
That's all we need, CHEERS!!
Top comments (2)
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:
webpack -w
or the webpack-dev-server.ok, found the error, was using app/assets/images/ and not app/javascript/images/, doh :)