Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Entry, Output and Loaders

Loaders Basics

Learn how Webpack loaders turn CSS, images, TypeScript and any file into modules: module.rules, test and include, loader chains, options, and how to write a tiny custom loader.

Out of the box, Webpack understands only JavaScript (and JSON). That sounds limiting, but it is the whole design: a loader is a function that receives the source of a file and returns something Webpack can use, usually JavaScript. A loader turns Sass into CSS, TypeScript into JavaScript, or a Markdown file into a string. Because every file type goes through the same pipeline, import './styles.css' and import logo from './logo.svg' just work once you configure the right loaders.

Rules: matching files to loaders

You declare loaders in module.rules. A rule says: for files matching this condition, run these loaders.

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

The condition keys:

Key Meaning
test a RegExp (or function) matched against the file path
include only files inside these folders
exclude skip files inside these folders (commonly node_modules)
resourceQuery match the ?query part of an import
issuer match who imported the file
oneOf first matching sub-rule wins

Use include rather than exclude when you can; positive lists are faster and clearer. Remember that test is a regular expression, so escape the dot: /\.css$/.

Chains run from right to left

When use is an array, loaders form a pipeline. The last loader runs first and passes its result to the one before it. For ['style-loader', 'css-loader', 'sass-loader']:

  1. sass-loader compiles Sass to plain CSS.
  2. css-loader resolves @import and url() and turns the CSS into a JavaScript module.
  3. style-loader injects that CSS into the page with a <style> tag at runtime.
flowchart RL
  F["styles.scss"] --> S["sass-loader"]
  S --> C["css-loader"]
  C --> T["style-loader"]
  T --> J["JavaScript module"]

Read the array from the right: each loader hands its output to the next.

Node.js Stand-in: a loader chain, right to left

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Loader options

A loader written as a string uses defaults. Use an object to pass options:

JavaScript
{
  test: /\.css$/i,
  use: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,   // run the next loader on @imported files too
        modules: true,      // enable CSS Modules
        sourceMap: true,
      },
    },
    'postcss-loader',
  ],
}

Each loader documents its own options, and Webpack validates them just like the main config.

Built-in alternatives: asset modules and type

Webpack 5 handles many cases without loaders. A rule can set a type, such as asset/resource for files that should be copied and given a URL, or json, asset/inline and asset/source. These replace the old file-loader, url-loader and raw-loader (Asset Modules).

JavaScript
{ test: /\.(png|jpe?g|svg)$/i, type: 'asset/resource' }

Writing a custom loader

A loader is a CommonJS module that exports a function. this offers helpers, and the function returns the transformed source.

JavaScript
// loaders/markdown-lite-loader.js
module.exports = function (source) {
  const html = source
    .replace(/^# (.*)$/gm, '<h1>$1</h1>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  return `export default ${JSON.stringify(html)};`;
};

Register it with a path:

JavaScript
{
  test: /\.md$/,
  use: path.resolve(__dirname, 'loaders/markdown-lite-loader.js'),
}

Then import html from './intro.md' gives you the converted string. Real loaders also can be async (this.async()), report errors, add file dependencies for watching, and return source maps, but this shape is the essence.

Node.js Stand-in: run a custom Markdown loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Order of rules and enforce

If several rules match one file, all their loaders run. To control ordering across rules, use enforce: 'pre' (runs first, good for linting) or enforce: 'post'. Inside a single rule, the array order decides, right to left. If a transformation seems to be skipped, check that the rule's test matches and that no oneOf earlier branch won.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In use: ['style-loader', 'css-loader', 'sass-loader'], which loader runs first?

    Loader chains run from right to left, so sass-loader compiles first and style-loader runs last.
  2. 2. What does the test field of a rule contain?

    test decides which files the rule applies to.
  3. 3. What does a loader function receive and return?

    A loader transforms a source string into something Webpack can use, typically a JS module.
  4. 4. Which rule type replaces file-loader and url-loader in Webpack 5?

    Asset modules are built in, so those loaders are no longer needed.

Summary

  • Loaders transform files into modules; they are declared in module.rules with test, include, exclude and use.
  • Loader arrays run right to left, and each result feeds the next.
  • Options are passed with an object form { loader, options }.
  • Webpack 5 asset modules handle images, fonts and raw text without extra loaders.
  • A custom loader is a function from source to source; this is a stand-in for how Webpack calls it.

Next: CSS and Style Loaders