Webpack:从嵌入式样式加载图像(背景图像) [英] Webpack: load images from inline style (background-image)

查看:186
本文介绍了Webpack:从嵌入式样式加载图像(背景图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with loading an image using webpack.

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

When I use an image tag on an html page, everything works fine:

 <img src="../../content/images/logo.png">

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

But I also have a need to use inline styles:

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

在这种情况下,webpack不会解析图像,并且使url()中的字符串保持不变.

In this case, webpack doesn't resolve the images and leaves the string in the url() untouched.

Webpack配置:

Webpack config:

        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]']
            }
        ]
    },

如果有人可以帮助我解决此问题,我将不胜感激.

I would be grateful if someone could help me with this issue.

推荐答案

您可能需要带有已启用插值标记:

require("html-loader?interpolate!./your-file.html");

...,然后要求您插入样式的背景图片,例如:

...and then require your inlined-style background image like:

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

这篇关于Webpack:从嵌入式样式加载图像(背景图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆