Adding CSS and Assets to webpack

You might want to use a lot of static file assets via Webpacker, such as images or fonts, in your code or CSS. To get those assets into our pack file we have to import them, and then Webpacker gives us some helper methods to be able to access the files. We need helper methods here because bundling the images into the pack changes the name of the file, so we can’t just use the raw file name.

First we need to import the static files. To do so, we need to add the following code to our application.js. This code is boilerplate from the Webpacker gem, which I removed along the way; we can put it back now:

 const​ images = require.context(​"../images"​, ​true​)
 const​ imagePath = (name) => images(name, ​true​)

The first line is the important one: it uses the webpack require.context method to add the entire ../images directory into our pack—that’s the relative name for the app/packs/images directory. One important piece here is that the app/packs/images directory must actually exist, or TypeScript will fail to compile.

Any files placed inside that subdirectory are then available to the pack when the pack is compiled. We can do separate require.context calls for other directories if we want to add items like fonts, or video, or whatever.

The last line creates a method called imagePath that you can then export or use in other JavaScript code to get the name of the file.

At this point, we have a few ways to access any image file in that images subdirectory.

From JavaScript code, we can use that imagePath function we just defined, which looks like imagePath("./arrow.png") (you need the ./ for the method to work). We can also import the image file as import FileName from "images/file_name.svg" and then use the imported name as the source of an image file.

From our SCSS files, we can reference the image directly, relative to the file we are in, and webpack will handle the reference correctly. If we wanted to use an image as a background image in a style defined in our packs/application.scss file, it’d look like background-image: url("../images/arrow.svg");. We can directly reference the image file relative to application.scss.

Inside a Rails view, Webpacker defines two helper methods: asset_pack_path, which takes in the location of a file in the file system and returns its Webpacker name, and image_pack_tag, which is a replacement for image_tag, as in image_pack_tag("arrow.png").

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset