Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url-loader vs File-loader Webpack

I'm trying to figure out the difference between url-loader vs file-loader. What does DataURl mean?

The url-loader works like the file-loader, but can return a DataURL if the file is smaller than a byte limit.

like image 885
stackjlei Avatar asked Mar 03 '18 02:03

stackjlei


People also ask

What is URL-loader in webpack?

Webpack's url-loader lets you import arbitrary files, like images. If you import a . png file, url-loader will ensure that import resolves to a Base64 string representing the contents of the file.

What does file loader do in webpack?

Webpack file-loader is a loader used mainly for supporting images such as SVG and PNG, and fonts in your webpack project. If your images are not loading in your webpack app then you probably miss the configuration of file-loader.

How do I load an image with a webpack loader?

You could solve this in two ways: Run all your code under the "dist" folder. Add publicPath property to your output config, that points to your output directory (in your case ./dist).


2 Answers

url-loader will encode files to base64 and include them inline rather than having them loaded as separate files with another request.

A base64 encoded file may look something like this:

data:;base64,aW1wb3J0IFJlYWN0IGZ... 

This would be added into your bundle.

like image 65
jens Avatar answered Oct 05 '22 03:10

jens


Just wanted to add to Jens' anwer

file-loader will copy files to the build folder and insert links to them where they are included. url-loader will encode entire file bytes content as base64 and insert base64-encoded content where they are included. So there is no separate file.

They are mostly both used for media assets such as images. Mostly images.

This technique may make page load faster because there are fewer http-requests to the server to download files.

It's also important that you can specify size limit for url-loader. It will automatically fall back to file-loader for all files beyond this size:

{     test: /\.(png|jpg|gif)$/i,     use: [{         loader: 'url-loader',         options: {             limit: 8192 // in bytes         }     }] } 
like image 29
Gherman Avatar answered Oct 05 '22 03:10

Gherman