Learn

Let’s take a look at how images can be bundled with Webpack.

Since Webpack 5, images and fonts no longer need a loader, and can use Webpack’s asset system. Their rules are similar to that of .txt files.

{ test: /\.png$/i, type: 'asset/resource' }

Notice we use type with asset/resource rather than asset/source. asset/resource creates a file in the build and imports it into the code as a URL. You may want to explore more about asset types. The rule above would only match with *.png files, but we could have it handle many image types:

{ test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource' }

When an image rule has been defined in webpack.config.js, we can import images into our JavaScript as if they were code:

import Square from '../square.png'; const img = document.createElement('img'); img.src = Square; const body = document.querySelector('body'); body.appendChild(img);

When we build, the image is in the site!

Let’s practice adding image resources to our Webpack project.

Instructions

1.

Get started by making a rule for images in webpack.config.js that handles .png files.

2.

Import theBanner image at ./Banner.png as Banner.

Set the src of the img element to Banner.

3.

We are ready to build!

Run the build command in one terminal.

4.

Let’s take a look at our banner!

In a different terminal, run the start command, then refresh the preview on the right.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?