1

I have an app structure like this:

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

The app.js file content is:

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

The src/styles.css file content is as follows:

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

So, the js file requires the css file. And css file requires png file.

I want 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 filenames are not important. The public folder output is what important. Css file is exported as a separate file, it contains the proper path to the image. The JS file knows the path of the public css file.

If there was no image present, the file-loader could be used to import css file. But in my case css file has first to be processed by css-loader in order to resolve the url() path.

Applying css-loader before the file-loader breaks things because returns JS code instead of CSS.

Is there a way to build a pipe to achieve the wanted result?

1 Answer 1

2

I think you are looking for Extract Text Plugin. The name may sound a little… off, but it essentially does what you described.

You can use multiple loaders with it to resolve image paths, process SCSS, autoprefix properties etc.

Sign up to request clarification or add additional context in comments.

2 Comments

ExtractTextPlugin does not allow me to return the url to the css file when I import it in JavaScript
Got the desired result by applying ExtractTextPlugin. But had to exclude the emitted css from HtmlWebpackPlugin configuration. Because the latter included the styles into the page, and I didn't want that. I wanted to only get the url of the css file to load it manually. The only drawback here is that the url of the emitted file is static and my code now is aware of it. It does not get the url by require('path/to/source')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.