Lesson 18 / 25
Custom loaders and plugins
Write your own loaders and plugins.
Extending Webpack
Custom loaders are functions that transform content. They receive source code and return transformed output. Custom plugins are classes implementing apply() method, hooks into Webpack compiler. Both allow you to 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?
- Source code content of a file.
- The file path only.
- Compiled JavaScript output.
Answer
Source code content of a file. — Loaders receive the file content as a string and return transformed content, enabling flexible file processing.