Amir Shahbabaie
Amir Shahbabaie

Reputation: 1412

webpack file-loader load all files in a folder

I have a bunch of images in a folder and webpack file-loader loads only those referenced inside the html or css files. thats's fine. But I want all the images in the folder to be loaded in the final dist/images folder as well, wheter they are addressed inside html or not.

The point is I want to load them by user click one after another

Thanksssssssss

Upvotes: 4

Views: 1631

Answers (2)

Kim Skogsmo
Kim Skogsmo

Reputation: 479

I stumbled upon this problem today, and after some searching, I saw a lot of different answers.

The solution using require.context() to recognize images in a folder assumes you are running node on the server. In our case, we are only using webpack to bundle files for a .NET Core MVC app.

Regardless of your particular scenario, simply referring the images in an unused class declaration would seem the most easy and intuitive way for me. It doesn't matter at all that we are overwriting the background-image property.

.--webpack-detect-images {
    background-image: url('./assets/images/file1.png');
    background-image: url('./assets/images/file2.png');
    background-image: url('./assets/images/file3.png');
}

Upvotes: 0

Tom Van Rompaey
Tom Van Rompaey

Reputation: 3586

You can force Webpack to require every asset from a certain folder.

Put following code inside the entry point of your application:

// load assets
function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('images/', true));

Upvotes: 3

Related Questions