Webpack:从内联样式加载图像(背景图像)

Vla*_*lev 4 javascript webpack webpack-html-loader webpack-2

我在使用 webpack 加载图像时遇到问题。

当我在 html 页面上使用图像标签时,一切正常:

 <img src="../../content/images/logo.png">
Run Code Online (Sandbox Code Playgroud)

但我也需要使用内联样式:

<div style="background-image: url('../../content/images/logo.png')">
Run Code Online (Sandbox Code Playgroud)

在这种情况下,webpack 不会解析图像并将字符串留在 url()原样中。

网络包配置:

        module: {
        rules: [
            { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },
            {
                test: /\.ts$/,
                loaders: [
                    'angular2-template-loader',
                    'awesome-typescript-loader'
                ],
                exclude: ['node_modules/generator-jhipster']
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
                options: {
                    minimize: true,
                    caseSensitive: true,
                    removeAttributeQuotes:false,
                    minifyJS:false,
                    minifyCSS:false
                },
                exclude: ['./src/main/webapp/index.html']
            },
            {
                test: /\.scss$/,
                loaders: ['to-string-loader', 'css-loader', 'sass-loader'],
                exclude: /(vendor\.scss|global\.scss)/
            },
            {
                test: /(vendor\.scss|global\.scss)/,
                loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader']
            },
            {
                test: /\.css$/,
                loaders: ['to-string-loader', 'css-loader'],
                exclude: /(vendor\.css|global\.css)/
            },
            {
                test: /(vendor\.css|global\.css)/,
                loaders: ['style-loader', 'css-loader']
            },
            {
                test: /\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/i,
                loaders: ['file-loader?hash=sha512&digest=hex&name=/images/[hash].[ext]']
            }
        ]
    },
Run Code Online (Sandbox Code Playgroud)

如果有人能帮助我解决这个问题,我将不胜感激。

And*_*aro 7

您可能需要启用插值标志的“ html”文件:

require("html-loader?interpolate!./your-file.html");
Run Code Online (Sandbox Code Playgroud)

...然后需要您的内联样式背景图像,例如:

<div style="background-image: url('${require(`../../content/images/logo.png`)}')">
Run Code Online (Sandbox Code Playgroud)