Having trouble with webpack displaying CSS background images?

I've set up the html boilerplate using webpack. I'm currently encountering an issue where calling an image in my scss file like "background: url('/img/img.png');" isn't working. I've included the webpack file and folder structure for reference. I attempted to use "url-loader" but it also didn't solve the problem. I've spent a lot of time trying to resolve this, but unfortunately, I haven't found a solution yet. Could someone please assist me in fixing this issue?

This is how my folders are structured:

Project
     |   
     +-- html
     |  |  
     |  +-- css
     |  +-- img
     |  +-- js
     |  +-- index.html
     |    
     +-- src
     |  |  
     |  +-- js
     |  +-- scss

Webpack File

'use strict';
let webpack = require('webpack');
let path = require('path');
let nodeModulesPath = path.join(__dirname, 'node_modules');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
let exp = []; // multiple exports array

// Exports configs for each language
let configs = [
    {
        name: 'min',
        entry: './src/index.js',
        scssRule: {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract({
                use: [{
                    loader: "css-loader",
                    options: { minimize: true },
                },
                {
                    loader: "sass-loader",
                    options: { minimize: true },
                },
                ],
                fallback: "style-loader"
            }),
        }
    }
];

// Generate exports module for each config
for (let c of configs) {
    var e = {
        context: __dirname,
        watch: true,
        entry: c.entry,
        output: {
            path: path.resolve(__dirname, 'html/'),
            filename: "js/app.js"
        },
        module: {
            rules: [{
                enforce: 'pre',
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "jshint-loader"
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: [{
                        loader: "css-loader",
                        options: { minimize: true },
                    }],
                    fallback: "style-loader"
                }),
            },
            c.scssRule,
            {
                test: /\.(ttf|eot|woff|woff2|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '../[path].[ext]',
                    publicPath: '../',
                    emitFile: false
                },
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'file-loader',
                options: {
                    name: '../[path].[ext]',
                    publicPath: '../',
                    emitFile: false
                },
            }
            ]
        },
        plugins: [
            new ExtractTextPlugin({
                filename: 'css/app.css'
            }),
            new webpack.optimize.UglifyJsPlugin({
                compressor: { warnings: false }
            })
        ]
    }
    exp.push(e);
}

module.exports = exp;

Answer №1

To achieve the desired outcome, adjustments need to be made to the file-loader options. It is important for the file-loader to properly emit the file to the output directory instead of requiring manual copying of images, hence setting emitFile: false should be avoided.

In the current setup where the output directory is html/ and the file name template is ../[path].[ext], files end up outside the designated output directory (in the project's root directory). This is not ideal as the goal is to be able to deploy the output directory without any additional steps (the build directory acts as the server's root). Additionally, [path] only includes the path to the file, not the actual filename. To organize all images in html/img/, a better approach would be using name: 'img/[name].[ext]'.

The specified public path serves as a prefix for all paths, which proves beneficial when serving from a different base URL. For instance, if your app is served on /my-app/, requests for images should also follow the same structure like /my-app/img/name.png rather than just /img/name.png (public path resolves this issue). Refer to output.publicPath for more information.

The configuration for two different file-loader rules (one for fonts and one for images) could be set up as follows:

{
    test: /\.(ttf|eot|woff|woff2)$/,
    loader: 'file-loader',
    options: {
        name: 'fonts/[name].[ext]',
        publicPath: '/'
    },
},
{
    test:  /\.(jpe?g|png|gif|svg)$/i,
    loader: 'file-loader',
    options: {
        name: 'img/[name].[ext]',
        publicPath: '/'
    },
},

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

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Information vanishes on mobile devices

After creating a messaging app using React, TypeScript, and Firebase, everything works smoothly locally on both desktop and mobile. However, once the app is deployed, a problem arises specifically on mobile devices. The message input component ("sendMessa ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the ...

Guide to sending multiple checkboxes using jQuery AJAX in CodeIgniter

I'm encountering an issue with my code when I click the 'Simpan' button, the response in the URL is: Output in URL: localhost/rootappl/moduls/krs myCheckboxes%5B%5D=KFT106&myCheckboxes%5B%5D=KFT107&submit=Simpan HTML CODE: [IMG] ...

Embed a hyperlink within an informational passage

I have a search box with Ajax functionality like this; And I want to customize the NotfindText message to display as: "No results found, but you can try advanced search from here" However, I am struggling to add the link. I do not have much knowledge abo ...

Tap to reveal additional information with the power of Jquery and ajax

I have a question regarding the popup slide functionality. I would like to achieve the following: Currently, I am using the following code to display post details upon clicking: function getPostDetails(id){ var infoBox = document.getElementById("in ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Tips for assessing JSON response data from an AJAX form

I am struggling with how to properly structure a question, but I would like to explain my situation. I am using AJAX to send data and receiving JSON in return. Each value in the JSON response represents a status, and I need to test and react based on these ...

Challenges encountered when attempting to send an array in res.json with the MERN stack

I am facing a challenge while trying to make two separate model calls using the MERN stack. The issue arises when I try to send an array in res.json; extracting the data seems to be problematic. On examining the console log: {data: "[]", status: ...

Use jQuery to switch out certain text with specified HTML elements

I am looking to use jQuery in order to dynamically wrap any text that matches a specific regular expression with a particular HTML tag. For instance: <div class="content"> <div class="spamcontainer"> Eggs and spam is better than ham and spam. ...

Acquire the selected option's value and display it within a div container

Is there a way to extract and display only the price value (after the " - ") within a div with the id of "price", updating as the select element is changed? <select id="product-select" name=""> <option value="1">Product Name / Yellow / S - ...

PayPal's fast checkout page experiencing a billing problem

I'm experiencing a problem with my paypal express checkout where it won't allow guest-checkout without logging into paypal, despite having the necessary form fields: <input type="hidden" name="SOLUTIONTYPE" value="Sole" /> ...

employing flush for lodash's throttle wrapper

When using TypeScript with JavaScript and Angular: I am trying to use the throttle decorator from lodash to limit an API call while a user is navigating around the page, ensuring that it fires before they leave the site. In my TypeScript constructor, I h ...

Combining the p class with flexbox for optimal layout design

I have four flexed container boxes and I am looking to add text below them in a row. Does anyone have suggestions on how I can achieve this alignment, as well as tips for optimizing the code? .container { display: flex; flex-direction: row; just ...

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

Tips for retaining a number even when the page is refreshed

Is there a way to keep the number increasing even after refreshing the webpage? Currently, the number resets every time the page is refreshed. Any suggestions on how to fix this? Here is the number <form method="POST"> &l ...

Tips for validating the input type "password"

Below is the Jquery Script that I am using: $(document).ready(function(){ $("#myForm").validate({ rules: { username: { required:true }, password: { required:true ...

Displaying a large image within a small div using Bootstrap 4

I have a specific image with dimensions of 244px by 751px, and I am trying to place it inside a div container that is 132px by 132px. I want the image to maintain its aspect ratio without being stretched. Despite using the img-fluid class, the image does n ...

`Incorporating width and vertical alignment in an image`

I am trying to figure out a way to make the image fill up 100% of the width, aligning it vertically with the text below. The code I'm working on is for email newsletters using foundation. Check out my Example Site Unfortunately, I can't seem to ...