How to serve images using webpack?

Member

by deron , in category: Javascript , 5 months ago

How to serve images using webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 4 months ago

@deron 

To serve images using webpack, you can follow these steps:

  1. Install the required dependencies:
1
npm install --save-dev file-loader


file-loader is a webpack loader that allows you to handle various types of assets, including images.

  1. Configure webpack to handle images in your webpack.config.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
module.exports = {
  // ...
  module: {
    rules: [
      // ...
      {
        test: /.(png|svg|jpg|jpeg|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[hash].[ext]',
            },
          },
        ],
      },
    ],
  },
};


This configuration tells webpack to use the file-loader for any image file (with extensions .png, .svg, .jpg, .jpeg, .gif).

  1. Import and use the images in your JavaScript or CSS code:
1
2
3
4
5
import myImage from './path/to/image.png';

const imgElement = document.createElement('img');
imgElement.src = myImage;
document.body.appendChild(imgElement);


In this example, myImage holds the path to the image file, which is resolved by webpack and bundled along with the rest of the code.

  1. Start the webpack development server or build the project:
1
2
3
4
5
// For development
npx webpack serve

// For production
npx webpack


The images will be handled by webpack based on the configured setup, and you can access them in the browser through the served bundles.