D
D
dmitry20002021-08-05 11:05:20
webpack
dmitry2000, 2021-08-05 11:05:20

How to put pictures and fonts in separate folders in webpack 5 and work with them?

In webpack 5.6.0, images and fonts automatically go to the root of the project and the structure is mushy.
610b9b08350ef746290369.png
Previously, you could use the file-loader and do this:

{
        test: /\.(?:|gif|png|jpg|jpeg|svg)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: `./img/${filename('[ext]')}`
          }
        }],
      },

It still transfers everything normally, however, pictures, for example, are also transferred to the root and are no longer displayed on the site. How to do it right now so that pictures and fonts are in folders and everything works? I read the doc , but did not find examples with folders there

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2021-08-05
@dmitry2000

https://webpack.js.org/guides/asset-modules/#custo...

R
ruzzHammer, 2021-12-13
@ruzzHammer

Webpack 5 uses Asset Modules instead of the usual raw-loader, file-loader, url-loader. To return the behavior of the 4th version and use loaders, you can specify type: 'javascript/auto' in the rule.
More information at the link
I use the following config with asset modules to decompose images and fonts into different folders using generator:

module: {
    rules: [
     ....
      {
        test: /\.(woff|woff2|ttf|otf|eot)$/,
        type: 'asset/resource',
        generator: {
          filename: 'assets/fonts/[name][ext]'
        } 
      },
      {
        test: /\.(jpe?g|png|gif|svg|ico)$/,
        type: 'asset/resource',
        generator: {
          filename: 'assets/img/[name][ext]'
        } 
      }
     ....
    ],
  },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question