0

The problem is file-loader will always inject the same URL to the both HTML and CSS files.

I have got the flowing project structure

File structure

Webpack File-loader configuration

        {
            test: /\.(gif|png|jpe?g|svg)$/i,
            use: [{
                    loader: 'file-loader',
                    options: {

                        name: '[name].[ext]',
                        outputPath: "assets/images",
                        publicPath: '../images'

                    }
                }

            ]
        }

When I use publicPath: '../images' It will inject flowing URL to the HTML and CSS file

HTML

<img src='../images/[email protected]'/>

CSS

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

both URLs are the same but it's ok for the CSS file.

When I use publicPath: './assets/images' It will inject flowing URL to the HTML and CSS file

HTML

<img src='./assets/images/[email protected]' />

CSS

background-image: url(./assets/images/test-image.jpg);

both URLs are the same but it's ok for the HTML file.

Actually what I want to achieve is File loader will inject different URL to the HTML and CSS files.

Look like this

HTML

<img src='./assets/images/[email protected]' />

CSS

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

How can I configure Webpack for getting exactly above result

1 Answer 1

1

Paths to files can be easily resolved to absolute paths using the path module.

Add the following to the top of your webpack config, if not already present:

var path = require('path');

Then, you can use this to resolve absolute paths to different directories, depending on where the current working directory is. For example:

publicPath: path.resolve('assets', 'images')

The above should work perfectly to construct an absolute path to your assets/images folder. It won't give you the exact result that you're asking for in your question, but it should at least solve your problem. If it doesn't, please notify me so I can help you.

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

2 Comments

Now it's injected like this <img src='C:\Users\md-sh\Desktop\Webpack-stater-kit\assets\images/[email protected]' /> and it's not working
If there are more folders between the assets folder and your project directory, add them before the 'assets' in path.resolve call. (If it's only the dist folder, publicPath: path.resolve('dist', 'assets', 'images') should work.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.