Search code examples
webpack-3

Webpack favicons into different folder


I have two folders src/images/ and src/images/icons. All favicons are in png format.

In src/images/icons I put all the favicons for different devices, which I want to be webpacked to wwwroot/images/icons and all other images to wwwroot/images.

How can I separate images and favicons?

Now for images I have:

 {
            test: /\.(png|ico|svg|jpg|gif)$/,
            use: [
                'file-loader?name=/images/[name].[ext]'
            ]
        },

But this would copy all images to dist\images, including the icons, which should be one level deeper in folder dist\images\icons


Solution

  • There are several ways to do this (i.e. use test key against filename, separate rules, etc). However, here is one way that seems to work well and is fairly clear:

    const path = require('path')
    
    module.exports = {
      // ...
      module: {
        rules: [
    
          {
            test: /\.(png|ico|svg|jpg|gif)$/,
            exclude: /node_modules/,
            use: {
              loader: 'file-loader',
              options: {
                name: function(fullPath) {
                  return path.relative(__dirname + '/src', fullPath)
                }
              }
            }
          }
    
        ]
      }
      // ...
    }