Course contentsShow
← Web Development
Lesson 1391 of 2,98225. Build Tools and BundlersFree lesson

File and Asset Loaders

Handling images, fonts, and other static assets with file-loader and asset modules.

File and Asset Loaders

What You'll Learn

You'll learn how to configure Webpack to handle images, fonts, and other static files so they're properly processed, optimized, and included in your bundle.

Why Asset Loaders Matter

Just like style-loader processes CSS, Webpack needs special loaders to handle images, fonts, videos, and other non-JavaScript files. Without them, Webpack doesn't know what to do when your code imports a PNG or references a web font.

Think of asset loaders as customs agents for different file types—they check each file's "passport," determine how to process it, and decide whether to inline it, copy it, or transform it.

The Traditional Approach: file-loader

Historically, file-loader was the go-to solution. It copies files to your output directory and returns the public URL:

// webpack.config.js (older approach)
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: 'file-loader'
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: 'file-loader'
      }
    ]
  }
};

Modern Approach: Asset Modules

Webpack 5 introduced Asset Modules, eliminating the need for separate loaders:

// webpack.config.js (modern)
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|svg)$/,
        type: 'asset/resource' // replaces file-loader
      },
      {
        test: /\.(woff|woff2)$/,
        type: 'asset/resource'
      }
    ]
  }
};

Now when you import an image in your JavaScript, Webpack handles it automatically:

import logo from './logo.png';
// logo contains the public URL path

Key Takeaway: Asset modules (type: 'asset/resource') have replaced file-loader in Webpack 5+, providing built-in handling for images, fonts, and static files without extra dependencies.