How to handle dynamic image paths with webpack?

Member

by ryleigh , in category: Javascript , a year ago

How to handle dynamic image paths with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@ryleigh 

To handle dynamic image paths with Webpack, you can follow these steps:

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


  1. Extend your Webpack configuration by adding a new rule for images:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
module.exports = {
  // ...
  module: {
    rules: [
      // ...
      {
        test: /.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],
  },
};


  1. Import the image in your JavaScript file:
1
import imagePath from './path/to/image.png';


  1. Use the imported path in your code:
1
2
3
const image = new Image();
image.src = imagePath;
document.body.appendChild(image);


  1. Run webpack to bundle your code:
1
npx webpack


Webpack will automatically handle dynamic image paths and generate the appropriate URLs for them. The file-loader loader will copy the images to the output directory and return their new paths.


Note: Make sure to adjust the test property in the Webpack rule according to the types of images you want to handle.