简体   繁体   中英

Webpack file-loader inject the same URL to the HTML and CSS file

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

档案结构

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM