Skip to main content

What are Loaders?

Loaders are transformations that are applied to the source code of modules. They allow you to preprocess files as you import or load them. Loaders can transform files from different languages (like TypeScript) to JavaScript, or load inline images as data URLs.

How Loaders Work

Loaders are activated by using loadername! prefixes in require() statements, or are automatically applied via regex from your webpack configuration.
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  }
};

Loader Features

  • Loaders can be chained. Each loader in the chain applies transformations to the processed resource.
  • Loaders can be synchronous or asynchronous.
  • Loaders run in Node.js and can do everything that’s possible there.
  • Loaders can emit additional arbitrary files.

Execution Order

Loaders are evaluated/executed from right to left (or bottom to top):
use: ['style-loader', 'css-loader', 'sass-loader']
Execution order:
  1. sass-loader - Compiles Sass to CSS
  2. css-loader - Interprets @import and url() like import/require()
  3. style-loader - Injects CSS into the DOM

Loader Configuration

Using test

Match files using regular expressions:
{
  test: /\.css$/,
  use: 'css-loader'
}

Using include and exclude

Control which files are processed:
{
  test: /\.js$/,
  include: /src/,
  exclude: /node_modules/,
  use: 'babel-loader'
}

Passing Options

Pass options to loaders using the options property:
{
  test: /\.css$/,
  use: [
    { loader: 'style-loader' },
    {
      loader: 'css-loader',
      options: {
        modules: true
      }
    }
  ]
}

Common Loaders

Asset Loaders

file-loader and url-loader are deprecated in webpack 5. Use Asset Modules instead.

Writing Custom Loaders

Loaders are simple functions that take source content and return transformed content:
module.exports = function(source) {
  // Transform source
  return modifiedSource;
};

Loader API

Learn how to write custom loaders

Best Practices

  1. Keep loaders simple - Each loader should do one thing well
  2. Chain loaders - Combine multiple simple loaders instead of creating complex ones
  3. Use options - Make loaders configurable through options
  4. Cache results - Enable caching for better performance
  5. Avoid side effects - Loaders should be pure transformations

Performance Tips

  • Use include to limit the scope of loaders
  • Enable caching when available
  • Run loaders in parallel when possible
  • Use newer asset modules instead of deprecated loaders
Avoid using too many loaders as they can significantly impact build performance. Only use loaders when necessary.