Webpack文件加载器向HTML和CSS文件注入相同的URL

时间:2018-09-19 05:36:44

标签: javascript webpack webpack-4 html-webpack-plugin webpack-file-loader

问题在于文件加载器将始终向HTML和CSS文件注入相同的URL。

我有一个流畅的项目结构

File structure

Webpack文件加载器配置

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

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

                    }
                }

            ]
        }

当我使用publicPath时:“ ../ images” 它将向URL注入HTML和CSS文件

HTML

<img src='../images/team-1@2x.png'/>

CSS

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

两个URL都相同,但是对于CSS文件来说是可以的。

当我使用publicPath时:'./assets/images' 它将向URL注入HTML和CSS文件

HTML

<img src='./assets/images/team-1@2x.png' />

CSS

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

两个URL都相同,但对于HTML文件来说可以。

实际上,我要实现的是File loader将不同的URL注入HTML和CSS文件。

看起来像这样

HTML

<img src='./assets/images/team-1@2x.png' />

CSS

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

如何配置Webpack以获得完全高于结果的结果

1 个答案:

答案 0 :(得分: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.