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/team-1@2x.png'/>

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/team-1@2x.png' />

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/team-1@2x.png' />

CSS

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

How can I configure Webpack for getting exactly above result

Shifut Hossain
  • 1,599
  • 3
  • 14
  • 24

1 Answers1

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.

Rick
  • 1,172
  • 11
  • 25
  • Now it's injected like this and it's not working – Shifut Hossain Sep 19 '18 at 10:12
  • 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.) – Rick Sep 19 '18 at 10:22