Webpack will only load images that are referenced within CSS files, and it will not load images that are referenced within

Within my dist folder, you will find index.html, contact.html, index.js, contact.js, and two images referenced by my css as background images.

For example:

background-image: url("../images/prairie.jpg");

These are the only items in my dist folder. Any other images not mentioned in my css file are not loaded. These additional images are referenced solely within .js files (such as slideshow.js). The 'slideshow.js' file is a slideshow that does not display any images but instead shows a missing image icon. However, the background image previously mentioned ('../images/prairies.jpg') is displayed. All photos referenced in a css file are loaded into the dist folder, while those referenced only in a .js file and not a css file remain unloaded from the dist folder.

Below is my webpack.config.js:

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackTemplate = require('html-webpack-template');
const path = require('path');

const config = {
  mode: 'development',     
  entry: {
    index: './src/index.js',
    contact:'./src/contact.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              bypassOnDebug: true,
              disable: true,
            },
          },
        ],
      }
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      inject: true,
      chunks: ['index'],
      filename: './index.html'
    }),
    new HtmlWebpackPlugin({
      template: './contact.html',
      inject: true,
      chunks: ['contact'],
      filename: './contact.html'
    })
  ]
};

module.exports = config;

Answer №1

When incorporating webpack into your project and bundling images or assets, you cannot access them using the standard URL format such as /images/my-image.png.

This is because you are instructing your application to retrieve resources through the regular HTTP GET method instead of loading them via the bundle.

To access images within a webpack bundle, you should treat it like any other asset by using the require function. For example:

const image1 = require("images/image1.png")
. Internally, webpack converts the binary image into a data URI which allows you to then use it in HTML elements like this -> <img src={image1}/>

If you have multiple images, you can utilize the require.context, but personally I prefer having more control over loaded assets rather than using it.

To manage unconventional file names, you can configure webpack to generate logical filenames with added hash values. In your loaders configuration, specify something like ->

loader: 'file?name=[name].[ext]?[hash:5]'

UPDATE: If you are using the file-loader plugin, disregard the information about data URIs. When using the file-loader, webpack performs a type of remapping instead. Whether you use the file-loader or not, always make sure to use the require function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Caution: ToastAndroid is incompatible with this platform. A problem has occurred while using react native

Having trouble with this error in react native IOS: - node_modules/expo/build/logs/LogSerialization.js:166:14 in _captureConsoleStackTrace - node_modules/expo/build/logs/LogSerialization.js:41:24 in serializeLogDataAsync - ... 9 more stack frames from fra ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Failure to reset values in a Material-UI checkbox group (RHF)

After numerous attempts to reset my form using the reset() method, I have encountered a partial success. All fields in the form are reset except for the checkboxes group. Despite trying three different approaches to implementing an MUI CheckboxesGroup, th ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Creating a customized plugin in JavaScript that utilizes a local JSON/GeoJSON file

I am relatively new to Drupal and currently working on developing a custom map module. While my module functions correctly and displays the map along with relevant information, I encountered a challenge regarding calling my geojson file using a hard-coded ...

What is the correct CSS2 selector syntax to apply the :hover effect to the nth child of a specific element?

My goal is to apply a unique background color to each menu li element when hovered over, and I want to accomplish this using CSS2. <ul> <li> <li> <li> <li> </ul> I managed to add a background color to t ...

The dynamic import feature provides a different result of {$$typeof:...,render:f...} instead of the usual exported class

In my Next.js project, I am attempting to bring in the Quill module by using the following code: const Quill = dynamic(import("quill"), { ssr:false, }) However, when I log Quill, I am seeing a result of {$$typeof:...,render:f...} instead of the expect ...

Embed a photo into a pop-up window

Is there a way to dynamically insert an image into a Modal by utilizing the value of the variable data-image? This variable will change based on the selected image. <script type="text/javascript"> $('#myModal').on('show.bs.m ...

Guide to utilizing ref in a different component within a React Native application

I have incorporated MapboxGL in my application using React Native. import MapboxGL from "@mapbox/react-native-mapbox-gl"; <MapboxGL.MapView logoEnabled={false} attributionEnabled={false} ref={(e) => { this.oMap = e }} zoomLevel={6} cent ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

What are the steps to start a project on a personal computer?

Utilized on   - Windows 7, 64-bit I am interested in exploring how the project functions with github.com - project. Query: How can I get the project to do this? Steps Taken:   1. Saved the project to the directory. c:\test\visualStudio ...

Create a password variable while typing

Looking to avoid interference from browsers with autocomplete and password suggestions while maintaining the show/hide letters feature. The goal is to keep the password stored as a variable, regardless of whether the characters are shown or hidden. The is ...

How can PHP be used to access every element within an array that has been passed through an AJAX call?

I am having trouble accessing elements within an array from my PHP file after passing the array through an ajax call. Here is the code for the ajax call: var data = ['test1', 'test2', 'test3']; $(document).ready(function () { ...

What is the reason for having two distinct syntaxes for this in jQuery/bootstrap?

Here are two examples for handling events: $('.datepickerSelect').datepicker().on('changeDate', myFunction ); $(".datepickerSelect").datepicker( 'option' , 'onSelect', myFunction ); Can these event handlers be swap ...

What could be causing the lack of updates in the Redux state?

Everything looks good to me, the console logs are functioning in both the Action and Reducer. However, Chrome Redux tools do not display any triggered actions or state updates. Below is the Component Class: import React, { Component } from 'react&ap ...

Map Infobox appearing on page load

I am working on a Google map project where markers and info boxes dynamically populate when the user clicks on the map. However, I now need the info box to be loaded initially when the map loads, without requiring a click event. I have tried writing some c ...

The embedding feature is malfunctioning in the React application

I am trying to incorporate an HTML embed code into my React app. Here is the button within my functional component: import React from 'react' import './SideshiftStyle.css' export default function Sideshift() { return ( <div ...

Having trouble with Sequelize Single Instance not functioning properly after using Module.exports?

Here is my Sequelize Code snippet for database connection: var sequelize = new Sequelize('db-name', 'user', 'pwd', { host: 'XXX.XX.XX.XXX', dialect: 'mysql', pool: { max: 50, m ...

What are the best methods for resizing a video without altering its aspect ratio?

function initializeConstructor(props) { super(props); this.state = { screenWidth: Dimensions.get('window').width, heightScaled: null, }; } <View style={styles.videoView}> <Video sourc ...