All Posts

Let's Build: HTML5 Development Server & Build Tool With Webpack - Displaying Images

Welcome everyone to the fourth part of this tutorial series. Last week, we were able to display web fonts by creating a configuration using file-loader that enables webpack to understand web fonts that we declared in our css and include it to the output that’s being displayed in the browser.

Today, we’re going to use file-loader once again to add another critical component that we display in our websites: Images.

Webpack Configuration

To kick off our tutorial, open up webpack.config.js with the text editor of your choice. Upon opening the file, add these lines of code:

  //...
  //module: {
    //rules: [
      //...
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
          }
        ]
      },
      //..
  //...

When you add these lines of code in the list of loader configurations that you define inside module.rules, you are telling webpack that when it sees dependencies with file extensions of .png, svg, jpg,gif, use file-loader to process these to be displayed in the browser.

Just like last week, this configuration that we just added is very simple and we are not defining any destination directory because all these files that we intend to display in the browser using webpack are all in memory as of the moment. When we work on the last part of this tutorial series, I will be sharing to you in one go, all the webpack configuration changes that we will do to generate these dependencies in a similar fashion that we do when we build a static website manually.

Absolute Imports

Another update that we’ll be adding today within our Webpack configuration is adding the capability to do absolute imports. Once again, at the topmost of webpack.config.js, require the path core node module.

const path = require('path')

Next, before the output key inside webpack.config.js, add these lines of code to define absolute directory alias that points to the your_project_root/src/assets directory.

  resolve: {
    alias: {
      Assets: path.resolve(__dirname, "src/assets")
    }
  },
  //...  
  // output: {
  //   filename: '[name].bundle.js',
  //   publicPath: '/'
  // },

What’s happening here is that, every time we require a dependency with the Assets alias, Webpack will point that to /your_project_root/src/assets directory.

Absolute imports are extremely useful, specially when you are working on projects with nested directories. Requiring files from another directory that is relatively far from your current directory by doing something like require('../../../assets') is an additional hassle for someone who is trying to figure out where dependencies are located.

Adding an Image via HTML

Now that we’re done with making updates with our Webpack configuration, what we’ll be doing next is to add images with HTML using the <img> tag. To do this, let’s create the directory where all the images will be displayed.

  1. Open your your terminal and go to the root of your project directory and create a new directory called images inside /project_directory_root/src/assets.
cd /your_project_directory
mkdir -p ./src/assets/images
  1. Inside the images directory, select a logo of your choice. It can be either of svg, jpg, png, and gif. On this example i’ll be using this logo by Webpack as my logo. I saved it as icon.png.
  2. Using your text editor, open the home page HTML(./src/pages/index/index.html) and let’s make some modifications to load up the image logo that we just downloaded from the previous step.
<!-- index/index.html -->
<body>
<!-- Start of this new HTML -->
    <header class="max-w-lg mx-auto">
      <div class="w-24 mx-auto">
        <img src="<%= require('Assets/images/icon.png').default %>">
      </div>
    </header>
<!-- ...HTML after of this new HTML -->
</body>

You may be wondering: what’s going on with <%= require('Assets/images/icon.png').default %> inside the <img /> tag? This syntax is from the ejs templating engine that is provided by default, when you use html-webpack-plugin. This snippet is like how we require external css files inside index.js that is our entry point for the homepage. In this specific HTML file that we’re working on, we’re calling for the icon.png file as our dependency. When webpack processes that dependency, it generates an image that is in memory and it will replace that ejs template code with the URL that references where the image is located.

I would recommend that you try using your browser’s inspect tool on how Webpack has transformed the ejs template syntax into a URL.

  1. Using your terminal, on your project root directory, start up the development server with npm run start. After starting your development server, open your browser , visit http://localhost:3000 and you should be seeing your logo in the browser. With the logo of my choice this is how my home page looks like.

Image

Yay! 🎉 We have added an image through HTML.

Adding an Image via CSS

After we’ve covered adding images inside HTML, another common way of adding images to websites is through CSS. The most common reason why we add images with CSS is because we need to add a background image to our website. For the next steps, we’ll be going through how to add a background image in CSS using our development server.

  1. Pick a background image of your choice and from the root of your project directory, put it inside ./src/assets/images. For this example I will be downloading and using a background image from Subtle Patterns. To add, I will be naming my background image with bg.png.
  2. Inside ./src/pages/index/index.css, I add these lines of code to call your background image.
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Add these lines of code below */
body {
  background: #fff url('Assets/images/bg.png') 0 0 repeat;
}

As you can see, we are still using the alias Assets to call the images from /project_root_dir/src/assets/images.

  1. Once you’re done, restart once again the development server in your terminal with npm run start. Visit your browser, and you should see your background image being displayed. With my example, here is how it looks like:

Image

Congratulations, we successfully added image support to our development server. 🎉

Conclusion

That wraps up this part 4 of this series. I hope you learned something today about how to configure our development server to serve images with the help of file-loader. I encourage you to investigate and understand everything that’s happening with these changes that we made and adjust this configuration to what suits your development style. For the complete source code of this tutorial, please visit this github link.

Next week, I will be sharing to you how to create a new page and install 3rd party javascript libraries.

Have a blessed week to you!


Hi! If you have any questions, suggestions, corrections, or constructive feedback about this post, please let me know. I will greatly appreciate it!💯