Lesson 18 / 25

Custom loaders and plugins

Write a custom Webpack loader and plugin to add your own processing steps to the build pipeline.

Extending Webpack

Custom loaders are functions that transform content. They receive source code and return transformed output. Custom plugins are classes with an apply() method that hooks into the Webpack compiler. Both let you add custom processing to your build pipeline.

Write a custom loader

Create a simple loader that transforms text files.

module.exports = function(content) {
  const result = content.toUpperCase();
  return `export default ${JSON.stringify(result)}`;
};

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/,
        use: './loaders/uppercase-loader.js'
      }
    ]
  }
};

Output:

Loader transforms text file content to uppercase

Loaders are chainable

Multiple loaders process the same file sequentially. Each loader returns output that becomes input to the next. Order matters: right-to-left in the use array. This composability enables powerful, focused transformations.

Quick check

Quick check: What does a loader receive as input?

  • The file path only.
  • Compiled JavaScript output.
  • Source code content of a file.
  • The browser DOM tree.
Answer

Source code content of a file. — Loaders receive the file content as a string and return transformed content, enabling flexible file processing.