DEV Community

Shivashankar
Shivashankar

Posted on

Rails 6 - using images with webpacker and asset pipeline

Introduction:

Rails 6 by default now bundled with webpacker. Developers have choice to go for webpacker alone to use the images, css and js.

But there are cases where developers have to use both asset pipeline and webpacker.

The post is about how to deal these two things together, especially for the images.

Step: 1 - update application layout to include stylesheet_pack_tag

   <head>
     <%= stylesheet_link_tag 'application', media: 'all' %>
     <%= stylesheet_pack_tag 'application', media: 'all' %>
   </head>

Step: 2 - create folder structure as follows in app/javascript

app/javascript/
├── channels
│   ├── consumer.js
│   └── index.js
├── images
│   ├── 1.jpeg
│   ├── 2.jpeg
│   └── 3.jpeg
├── packs
│   └── application.js
└── src
    ├── custom.js
    └── stylesheets
        ├── _custom.scss
        └── application.scss

Assume we have few images 1.jpeg, 2.jpeg, 3.jpeg in images
folder.

Step: 3 - update src/stylesheets/application.scss as follows

@import '_custom';

Step: 4 - update packs/application.js as follows

require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")

// add these 2 lines
import 'src/stylesheets/application'
const images = require.context('../images', true)

Step: 5 - update config/webpacker.yml as follows

default: &default
...
...
// update: resolved_paths: [] as follows
resolved_paths: ['app/javascript/images', 'app/assets/images']
...

Now we are good to use images from both folders app/assets/images and app/javascript/src/images.

1. Using images in webpack css file (here: app/javascript/src/stylesheets/_custom.scss)

/* assume 1.jpeg present in app/javascript/src/images folder */
body{
  background-color: green;
  background-image: url("~1.jpeg");
}

/* assume lake.jpeg present in app/assets/images folder */
div{
  background-color: red;
  background-image: url("~lake.jpeg");
}

That's all. Now we can use both asset pipeline images and
webpack images together in our css.

2. Using images in rails views

# This is how we need to call image from app/javascript/src/images/2.jpeg path
<%= image_pack_tag "media/images/2.jpeg" %>
# This is normal way to call image present in app/assets/images folder.
<%= image_tag "lake.jpeg" %>

Note: In case if we need to share a same image between asset pipeline and webpack, then it is good to place the image in app/assets/images folder itself. It makes our life easy to call them in both asset pipeline css, views and webpacker js or css easily.

Oldest comments (0)