Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process involves using file-loader to handle font and image files, relocating them to suitable directories. I utilize the ExtractTextPlugin in combination with css-loader and resolve-url-loader to form a distinct css bundle from the javascript bundle.

The content of my main.js file:

import 'bootstrap/dist/css/bootstrap.css';
import 'chosen-js/chosen.css';
import './datetimehelper.js';
import './deletelink.js';
import './dropdown.js';

Here's a snippet from my webpack.config.js:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './src/js/main.js',
  output: {
    filename: 'wwwroot/js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader?url=false', 'resolve-url-loader'],
          publicPath: '../'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'wwwroot/css/bundle.css'
    })
  ]
};

In this setup, references to fonts in bootstrap.css are successfully processed, relocated, and corrected within the generated css bundle. However, the images mentioned in chosen.css are not being handled properly. Is there a solution to rectify this issue? Attempts such as replacing file-loader with url-loader or importing the images directly into main.js did not yield the desired outcome of correct rewriting of urls within the css bundle.

Answer №1

Setting up the path in the output configuration can greatly simplify your workflow. This will act as the main output folder, allowing other loaders and plugins to work relative to it. If you're having trouble with files being copied to the wrong directory, be sure to check out the Webpack Guide repository. The provided configuration properly handles image paths during copying and conversion.

Answer №2

After some trial and error, I finally cracked the code. The issue was in my initial rule declaration:

{
  test: /\.css$/,
  use: ExtractTextPlugin.extract('css-loader', 'resolve-url-loader')
}

But the correct syntax should have been:

{
  test: /\.css$/,
  loader: ExtratTextPlugin.extract('css-loader', 'resolve-url-loader')
}

I'm still learning the ropes of Webpack, so I'm not entirely clear on the distinction between use and loader. However, in this scenario, getting it right is crucial.

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

"Troubleshooting problems with the display:none property in a media

Encountering a small dilemma with media queries within my HTML. One of the sections in my code contains the following: <div class="header-left"> </div> <div class="header-center"> <ul> <li class="end"> ...

Is the "position: sticky" feature functioning correctly, or is there a slight vibrating or dancing effect when users scroll through the Ionic app? How can we eliminate this issue specifically on iOS

Looking for suggestions on this problem - the position sticky is functioning correctly, but there seems to be a slight vibration or dancing effect when users scroll in the Ionic app. Any ideas on how to eliminate this issue specifically on iOS devices? & ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

Revamp the website's design

I am looking to revamp the color theme of my website with just a click of a button. Can someone provide me with a link to a reference website where I can get some inspiration? ...

A guide to deactivating the Material UI Link API element

Previously, I relied on Material UI's Button component with a disable property that allowed the button to be disabled based on a boolean value. However, I now want to use the Material UI Link component, which resembles a text link but functions like a ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...

Adjusting padding evenly across an unspecified number of columns

I'm currently facing a challenge with a multi-column layout. In a basic setup of three columns, I aim to adjust the padding so that each gap between the columns is consistent (2rem). However, the tricky part lies in crafting rules that can be applied ...

Add custom CSS styles to a webpage using the CSS Style element retrieved from

I am working on an HTML page that has a TextArea and label. My goal is to create CSS classes in the TextArea and apply them to the label: <textarea id="txtCSS" name="txtCSS" rows="4" cols="50"> .FC{color:gr ...

Discover the secret to loading multiple Google charts simultaneously, despite the limitation that Google charts typically only allow one package to load at a time

I currently have a pie chart displaying smoothly on my webpage, but now I am looking to add a treemap as well. The code snippet for the treemap includes the package {'packages':['treemap']}. It has been stated that only one call should ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

Using JavaScript to transform radio buttons into checkboxes

I have a grouping of radio buttons and a checkbox displayed on the page as shown below <html> <head> <title>Languages</title> <script type="text/javascript"> </script> </head> <body> <spa ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

The discord.js argument for startsWith should not be a standard regular expression

What could be the reason behind this not working as expected? I am trying to check if a string starts with a number, and furthermore, I want it to handle multiple numbers. For instance, if the string starts with 1259823 then execute this code. I assume t ...

Having trouble displaying one DIV above another DIV

I'm having trouble getting an image in a DIV to display above text in another DIV. I can't figure out why it's only displaying below. <div> <div style='z-index: 99; width: 160px; height: 120px; box-shadow: 0px 0px 16px 0px r ...

Using async/await with Middleware in Express

I'm struggling to grasp the concept of writing middleware in Express that uses async/await without leaving a floating Promise after execution. Despite reading numerous blogs and StackOverflow posts, it appears that there is a common pattern for utiliz ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...