L
L
leviathan2022-03-21 00:07:52
webpack
leviathan, 2022-03-21 00:07:52

Webpack 5 and background-image inline?

How to force webpack 5 to include images that are specified inline.
Example:

<!--Работает-->
<img src="src/assets/img/test_image.jpg" alt="">
<!--Не работает-->
<div style="background-image: url('src/assets/img/test_image.jpg')"></div>

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')


module.exports = {
    mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',

    entry: {
        main: path.resolve(__dirname, './src/js/index.js')
    },

    output: {
        filename: 'js/index_bundle.js',
        assetModuleFilename: "assets/[hash][ext][query]",
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader'
            },
            {
                test: /\.(scss|sass|css)$/,
                use: [
                    (process.env.NODE_ENV === 'production') ? MiniCssExtractPlugin.loader : 'style-loader',
                    'css-loader',
                    'postcss-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            {
                test: /\.(woff|woff2)$/,
                type: 'asset/resource'
            },
            {
                test: /\.(png|jpg|svg)$/,
                type: "asset/resource"
            }
        ]
    },

    devServer: {
        static: {
            directory: path.join(__dirname, 'src/views')
        },
        port: 9000,
        compress: true,
    },

    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css'
        }),
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: __dirname + "/src/views/home.html",
            filename: "index.html",
            inject: 'body',
            hot: true
        }),
    ],
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
black1277, 2022-03-22
@The_Lars

There is one solution, but for pictures without a hash in the name (you just have to copy them to the right address),
background-image is inline,
but to be honest, it’s easier to straighten your arms for a layout designer who writes code using the 15-year-old method :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question