Adding CSS and Assets to webpack
Let's add CSS and assets to webpack.
We'll cover the following
Importing files
We might want to use a lot of static file assets from Webpacker, such as images or fonts, in our code or CSS. We have to import them to get those assets into our pack file. Then Webpacker gives us some helper methods to be able to access the files. We need helper methods because bundling the images into the pack changes the name of the file, so we can’t simply 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 a boilerplate from the Webpacker gem. This was removed for this course, but we can put it back now:
const images = require.context("../images", true)
const imagePath = (name) => images(name, true)
Explanation
The first line is the important one, using the webpack require.context
method to add the entire ../images
directory into our pack. s This is the relative name for the app/packs/images
directory. One important piece here is that the app/packs/images
directory must 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.
The last line creates a method called imagePath
that we can then export or use in other JavaScript code to get the name of the file.
Access Image Files
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")
(we 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 a file’s location in the file system and returns its Webpacker name image_pack_tag
, which is a replacement for image_tag
, as in image_pack_tag("arrow.png")
.
Get hands-on with 1400+ tech skills courses.