I have a problem with loading an image using webpack.
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')">
In this case, webpack doesn't resolve the images and leaves the string in the url() untouched.
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.
You might require your ´html´ file with interpolation flag enabled:
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`)}')">
                        Googled myself for solution, and decided to make a loader. https://github.com/apotap2/url-replace-loader It's just 20 lines of code :D it just that replaces every 'url(.*)' with require() so you can use it with file-loader. If you need more complicated logic it seems it's faster to make a loader yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With