Remove part of path for webpack file loader

Just in case you didn't solve this yourself: There is a useRelativePath option which allows to keep the relative path. Also, you can use a callback on the outputPath to change what it returns if you don't want things like ../ in there.

Doc on both things:

  • https://github.com/webpack-contrib/file-loader#userelativepath
  • https://github.com/webpack-contrib/file-loader#outputpath

With webpack 4 you can output to custom directory, in this case parent folder's directory, as follows:

  {
    test: /\.(png|jpe?g|gif|ico)$/,
    exclude: [/some-folder/],
    use: {
      loader: "file-loader",
      options: {
        name: `[path][name].[ext]`,
        // Output into parent folder's directory
        outputPath: url => url.slice(url.indexOf(`/`) + 1)
      }
    }
  }

Output path takes url, resourcePath, context as argument in that order.


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'
          }
      }]
  }