Exporting CSS file from css-loader in Webpack: A step-by-step guide

My application structure is set up like this:

/src
    /app.js
    /styles.css
    /images
           /img.png

The content of the app.js file is as follows:

const styles = require('./styles.css');
console.log(styles) // => I want a URL to the CSS file under the public folder

The content of the src/styles.css file looks like this:

.element {
  background: url(./images/img.png);
}

Therefore, the JavaScript file requires the CSS file, and the CSS file requires the PNG file.

I require all the files to be exported to the public folder:

public/app.js

const styles = 'styles.css' // => path to public/styles.css
console.log(styles)

pubic/styles.css

.element {
  background: url(img.png); /* path to public image file */
}

public/img.png (source image copy)

The specific filenames are not significant. What truly matters is the result in the public folder. The CSS file is exported independently with the correct path to the image. The JS file holds the path of the public CSS file.

If there were no image included, the file-loader could be utilized to import the CSS file. However, in my scenario, the CSS file must first go through the css-loader for the url() path resolution.

Implementing the css-loader prior to the file-loader creates issues because it returns JS code instead of CSS.

Is there a method to create a pipeline that achieves the desired outcome?

Answer №1

Have you considered utilizing the Extract Text Plugin? Despite its slightly misleading name, it actually performs the exact functionality you're seeking.

This plugin supports various loaders to handle tasks such as image path resolution, SCSS processing, and autoprefixing properties.

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

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

Removing accordion borders in Bootstrap and AngularJS can be achieved by customizing

Can anyone help me figure out how to hide the border in each accordion group that contains a panel and inner elements? I've tried using classes like .accordion and .inner but nothing seems to work. Any advice on where to find the specific class or ID ...

Reacts Router Link does not refresh page content

My React and Redux application features a Movie component that displays movie data fetched from an API. To enhance user experience, I decided to create a Similar Movies section at the bottom of the page. This section contains components that allow users t ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

How to dynamically change the color of an AngularJS element based on a condition?

As someone who is new to AngularJS, I am currently working on changing the color of a table element to yellow if the user has voted on a specific choice. <div ng-show="poll.userVoted"> <table class="result-table"> <t ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Retrieve the Vue object nested within another object and log it in the console

I have a variable called 'file' in my Vue application. When I use console.log to inspect its contents, it displays as shown in the image below: console.log(file); However, when I attempt to view the contents of 'exif' by using consol ...

Failed attempt to change background color using jQuery

Creating a new notification system where I need to highlight a specific comment once it has been scrolled to. I initially thought of implementing a background color change timeout, but I'm facing some issues with it... Check out this example: I hav ...

How to disable a specific array of dates in Ant Design range picker

Is there a way to block dates prior to the current date and specify certain dates that should also be disabled on the calendar? For example, I need to prevent selection of: Today: 2018-07-30 Dates to disable: [2018-08-10, 2018-08-12, 2018-08-20] When t ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

Is it possible for a scrollable div to fill the space above a BottomNavigation bar?

My current project involves creating a fixed bottom navigation bar, with a scrollable div above it displaying various card lists. In my attempts to achieve this layout, I consulted both the Material-UI documentation here and here. However, I struggled to ...