Search code examples
webpackwebpack-file-loader

Remove part of path for webpack file loader


I am setting up Webpack 3 and currently configuring asset management of static images that I would like to copy over from my src folder to my dist folder. I would like to keep the file structure of my /img folder in place as it copies over to the dist folder, but the issue I am running into is where I am trying to remove part of the path placeholder. Is what I am trying to achieve possible?

I have my rule as follows:

  {
      test: /\.(png|jpe?g|gif|ico)$/,
      use: [{
          loader: 'file-loader',
          options: {
              name: '[path][name].[ext]?[hash]',
              //outputPath: 'img/'
          }
      }]
  }

And it's grabbing images from my entry point file through the context:

require.context('./img/', true, /\.(png|jpe?g|gif|ico)$/);

However when the file gets copied over, because I have the [path] placeholder as part of the name, the files will resemble /src/img/[name].[extension]?[hash]. I would like to keep the rest of the path intact as some of the images have paths like /src/img/favicons/[name].[extension]?[hash] and I feel that the dist folder should maintain this structure. As you can see by the code I have tried to use the outputPath but this just sets the file to /img/src/img/[name].extension?[hash]. I have also tried utilizing the publicPath setting but it didn't seem to have any effect at all. The end goal would be to have the 2 files mentioned above not have the /src part of the file name included in this path.


Solution

  • The context option is what you are looking for, in your case:

      {
          test: /\.(png|jpe?g|gif|ico)$/,
          use: [{
              loader: 'file-loader',
              options: {
                  name: '[path][name].[ext]?[hash]',
                  context: 'src'
              }
          }]
      }