Url-loader vs File-loader Webpack

JavascriptWebpackUrlloaderWebpack File-Loader

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

Both answers are good but I want to further explain Data URL, check here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs, so its format is

data:[<mediatype>][;base64],<data>

For example, if I convert a mp3 file, it will look like following,

import audio from '../assets/media/audio.mp3';
console.log('base64 of my audio: ', audio); 

//with url-loader setup
//I will get something like "data:audio/mpeg;base64,xxx"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstackjleiView Question on Stackoverflow
Solution 1 - JavascriptjensView Answer on Stackoverflow
Solution 2 - JavascriptGhermanView Answer on Stackoverflow
Solution 3 - JavascriptQiulangView Answer on Stackoverflow