E
E
Evdokim2021-11-02 17:45:35
Less
Evdokim, 2021-11-02 17:45:35

How to solve the problem with loading background-images when building webpack?

I will immediately give fragments of configs and a compressed structure of the project. I am using the latest version of webpack, webpack-dev-server, css-loader and less-loader. Instead of url-loader and file-loader I use the built-in features of webpack 5 (asset/resource and asset/inline).

Less file loading rule (webpack):

{
  test: /\.less$/,
  exclude: path.resolve(__dirname, 'node_modules'),
  use: [
    isProd ? MiniCssExtractPlugin.loader : "style-loader",
    {
      loader: 'css-loader'
    },
    {
      loader: 'postcss-loader',
      options: {
        postcssOptions: {
          plugins: [
            "postcss-flexibility",
            ["postcss-preset-env", { browsers: browserList }],
          ]
        }
      }
    },
    {
      loader: 'less-loader',
      options: {
        lessOptions: {
          includePaths: [
            // тут некоторые пути
          ]
        }
      }
    }
  ]
},


Image loading rule (webpack):
{
  test: /\.(png|jpe?g|gif)$/,
  type: 'asset/resource',
  generator: {
    filename: isProd ? 'files/[name]-[contenthash].[ext]' : 'files/[name].[ext]'
  },
},


To run the configuration I use webpack-dev-middleware :
const compiler = webpack(config);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    stats: config.stats
  })
);


The condensed structure of the project is as follows:
project
  |
  |---src
  |     |---SomeComponent
  |     |---styles.less
  |---images
  |     |---main-logo.png
  |---webpack.config.js
  |---package.json


Style snippet in styles.less file :
.main-logo-container {
  background-image: url(/images/main.logo);
}


The problem is that when starting the project (dev and build), webpack swears that it cannot find the images/main.logo file specified in the styles.less style file:
Module not found: Error: Can't resolve '/images/main.logo' in 'project/src'


As far as I understand, if you put the images folder inside src, then there should be no problems, but unfortunately there is no way to put it there. How to solve this problem with such folder structure?

Thanks in advance for the tips.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question