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 usingloadername! prefixes in require() statements, or are automatically applied via regex from your webpack configuration.
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):sass-loader- Compiles Sass to CSScss-loader- Interprets@importandurl()likeimport/require()style-loader- Injects CSS into the DOM
Loader Configuration
Using test
Match files using regular expressions:
Using include and exclude
Control which files are processed:
Passing Options
Pass options to loaders using theoptions property:
Common Loaders
Babel Loader
Transform modern JavaScript and JSX
TypeScript Loader
Compile TypeScript to JavaScript
CSS Loader
Load and transform CSS files
Sass Loader
Compile Sass/SCSS to CSS
Asset Loaders
file-loader and url-loader are deprecated in webpack 5. Use Asset Modules instead.- file-loader - Emit files to output directory (deprecated)
- url-loader - Encode files as data URLs (deprecated)
- raw-loader - Import files as strings
Writing Custom Loaders
Loaders are simple functions that take source content and return transformed content:Loader API
Learn how to write custom loaders
Best Practices
- Keep loaders simple - Each loader should do one thing well
- Chain loaders - Combine multiple simple loaders instead of creating complex ones
- Use options - Make loaders configurable through options
- Cache results - Enable caching for better performance
- Avoid side effects - Loaders should be pure transformations
Performance Tips
- Use
includeto limit the scope of loaders - Enable caching when available
- Run loaders in parallel when possible
- Use newer asset modules instead of deprecated loaders