Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use file-loader when using url-loader with limit option?

Using webpack-4

As far as I understood, the url-loader will have the same behavior than the file-loader if you set the limit option (it uses it under the hood), I noticed my image loading was broken when I used the conf below

{test: /\.(jpe?g|gif|bmp|mp3|mp4|ogg|wav|eot|ttf|woff|woff2|png|svg)$/, use: 'url-loader?limit=10000'}

{test: /\.(jpe?g|gif|bmp|mp3|mp4|ogg|wav|eot|ttf|woff|woff2|png|svg)$/, use: 'file-loader'}

when I remove the file-loader it's working fine, url-loader is catching everything **you need. A few questions below:

  1. In the conf above file-loader is breaking url-loader behavior (probably because I don't clearly specify the output folder) Am I understanding it well ?

  2. what are the cases you really need file-loader ?

  3. what are the cases when it's good to do a combination of both (if any) ?

like image 978
François Richard Avatar asked Mar 04 '23 08:03

François Richard


1 Answers

  1. In the conf above file-loader is breaking url-loader behavior (probably because I don't clearly specify the output folder) Am I understanding it well ?

When defining both loaders you will have the behaviour of both, which is to encode all files in-place into base64 strings when their size is < 10000 bytes AND to copy all of them into your distribution directory.

You were right to remove the file-loader loader declaration if the behaviour you want is you want is to either encode as base64 when size < 10000 bytes OR copy to distribution folder when size > 10000 bytes.

Because url-loader has a fallback option, and it's default value is file-loader, the second file-loader declaration is unnecessary IF the files being targeted are the same for each loader.

  1. what are the cases you really need file-loader ?

Whenever you want to copy a file to your dist directory and have reference to this file's location in the public path (where static assets will be served from; the publicPath webpack conf. property) within your bundled application. For example if you configured file-loader to copy images and name them as [hash].[ext] you can do:

const img = require('avatar.jpg')
console.log(img) // => /public/[hash].jpg
  1. what are the cases when it's good to do a combination of both (if any) ?

Use both if you have files you always want to copy (file-loader) and files that you may want to encode into your bundle files (url-loader). Be careful not to target the same file types with both loaders, otherwise you may be copying files over that are also being encoded into your bundles with url-loader.

like image 92
sdgluck Avatar answered May 06 '23 13:05

sdgluck