Loaders — a guide to processing assets

Learn what loaders do, when to use them, their execution order, and how to process assets with style-loader, css-loader, file-loader, and babel-loader.

🎯 Introduction

This article explains what loaders are and how they load and process different types of resources. You will configure style-loader and css-loader for CSS, load images with file-loader or webpack 5 asset modules, and transpile modern JavaScript with babel-loader for broader browser compatibility. These tools help you build an efficient frontend build workflow.


📦 What are loaders? Use cases and execution order

A loader is a transformation tool that preprocesses files in webpack. Loaders can process non-JavaScript resources such as CSS, images, and fonts, as well as transform modern JavaScript features into code that target browsers understand.

Loaders turn the code you write into code browsers can run. Think of a translator who takes a letter written in one language and translates it for readers of another language.

Use cases

You can use loaders to:

  • Load CSS and insert styles into a page
  • Process static assets such as images and fonts
  • Transpile modern syntax or JSX
  • Process TypeScript files

Execution order

When webpack encounters a matching file, it passes it to the configured loaders. When multiple loaders are chained, they execute from right to left (or bottom to top).

For example:

{
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
}

Here, css-loader first converts the CSS file into a JavaScript module, then style-loader inserts its styles into the page. Reversing the order prevents the chain from processing the CSS correctly.

Loaders form a chain: the loader listed first runs last, and the loader listed last runs first.

🎨 Load CSS with style-loader and css-loader

Browsers can load CSS directly, but single-page applications and modular projects often need to manage CSS as modules alongside JavaScript. webpack's css-loader and style-loader make this possible.

  • css-loader converts CSS files into JavaScript modules, resolving syntax such as @import and url() so CSS can be imported from JavaScript.
  • style-loader dynamically inserts those styles into <style> elements, applying them to the page.

Example configuration

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
};
Install the loaders with npm before using them, for example: npm install style-loader css-loader.

How it works

When you write the following in JavaScript:

import './style.css';

webpack uses css-loader to parse the CSS and turn it into JavaScript, then uses style-loader to insert the styles into the page's <head>.

Code example

index.js
import './style.css';

console.log('Hello Loader!');
style.css
body {
    background-color: #f0f0f0;
    font-family: Arial, sans-serif;
}
<!-- Load the JavaScript bundle to apply the styles automatically -->
<script src="bundle.js"></script>
To extract CSS into a separate file, for example in production, replace style-loader with MiniCssExtractPlugin.

🖼️ Load images with file-loader or asset modules

Images are essential frontend assets, and webpack offers several ways to load them.

Traditional approach: file-loader

file-loader copies assets such as images to the output directory and returns their final URLs for use in your code.

Example configuration:

module.exports = {
    module: {
        rules: [
            {
                test: /\.(png|jpg|gif|svg)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[hash:8].[ext]',
                            outputPath: 'images/',
                        },
                    },
                ],
            },
        ],
    },
};

This approach offers flexibility and support across webpack versions.

Introduced in webpack 5: asset modules

In webpack 5, built-in asset modules replace file-loader and url-loader, reducing dependencies and simplifying configuration.

module.exports = {
    module: {
        rules: [
            {
                test: /\.(png|jpg|gif|svg)$/,
                type: 'asset',
                parser: {
                    dataUrlCondition: {
                        maxSize: 8 * 1024, // Inline images up to 8 KB as base64 to reduce requests
                    },
                },
                generator: {
                    filename: 'images/[name].[hash:8][ext]',
                },
            },
        ],
    },
};

Explanation

  • Images smaller than 8 KB are inlined as base64 data to reduce requests
  • Larger images are copied to the output directory, and their URLs are returned

Code example

import logo from './logo.png';

const img = document.createElement('img');
img.src = logo;
document.body.appendChild(img);

This displays the image on the page.

Choose the size threshold carefully when using asset modules to avoid oversized bundles.

🛠️ Transpile modern JavaScript with babel-loader

Modern JavaScript includes features such as arrow functions, async/await, and module syntax, but browser support varies. babel-loader lets you transform modern JavaScript into more widely compatible code, including ES5 where needed.

Configuration

First, install the Babel dependencies:

npm install -D babel-loader @babel/core @babel/preset-env

Then configure webpack.config.js:

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
        ],
    },
};

Also create a .babelrc configuration file:

{
    "presets": ["@babel/preset-env"]
}

What it does

  • @babel/preset-env transforms code to suit your configured target browsers.
  • Use the browserslist field in package.json to specify target environments.

Example

Write a function using arrow syntax:

const add = (a, b) => a + b;
console.log(add(1, 2));

After babel-loader processes it for older browsers, the output uses a regular function instead.

Babel transpilation increases build time. Enable caching or limit transpilation to the code that needs it when building for production.

❓ Questions and answers

Q1: In what order do loaders execute?

Loaders execute from right to left, or bottom to top. The first loader listed runs last, and the last loader listed runs first.

Q2: Why transpile code with babel-loader?

Browsers support different sets of JavaScript features. babel-loader transforms modern syntax into more compatible code so it can run in more browsers.


🧪 Exercises

Exercise 1

Configure a webpack project to load a local CSS file and apply its styles using style-loader and css-loader.

index.js
import './main.css';

console.log('Testing CSS loading');
main.css
body {
    color: blue;
}

Exercise 2

Use babel-loader to transpile JavaScript containing arrow functions, and verify that it runs in a browser without support for that syntax.

const greet = name => `Hello, ${name}!`;
console.log(greet('Loader'));

🎉 You now understand loaders, style-loader, css-loader, file-loader, asset modules, and babel-loader! Use them to configure asset processing and improve your development workflow and browser compatibility.