Loaders
Out of the box, Webpack only understands JavaScript and JSON files. However, in real-world web projects, you use various file formats such as CSS, images, TypeScript, etc. Loaders allow Webpack to process these different types of files and convert them into modules.
Major Loader Types
- CSS/Styles:
css-loader,style-loader,sass-loader,postcss-loader - Transpilers:
babel-loader,ts-loader - File Asset Resources:
file-loader,url-loader(Note: These are being replaced by Asset Modules starting from Webpack 5.)
How to Configure Loaders
You define loader rules within the module.rules array in your webpack.config.js file.
module.exports = {
// ... omitted ...
module: {
rules: [
{
test: /\.css$/, // Matches any file ending in .css
use: ['style-loader', 'css-loader'], // Applied from right to left
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
}
],
},
};
It is important to note that loaders are executed in reverse order (from right to left or bottom to top) in the array.