Lesson 4 / 25

Loaders and rules

Teach Webpack how to process different file types.

What loaders do

Webpack natively understands only JavaScript. Loaders transform other file types into valid modules. They work with file patterns (test) and apply transformations (use). Common loaders include babel-loader for JavaScript transpilation, style-loader for CSS, and file-loader for assets.

Configure loaders

Add module rules to process CSS and JavaScript with transpilation.

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: { presets: ['@babel/preset-env'] }
        }
      }
    ]
  }
};

Output:

Loaders process files matching test pattern left-to-right

Loader order matters

Loaders execute right-to-left in the 'use' array. For CSS, css-loader parses the CSS, then style-loader injects it into the DOM. Reversing the order breaks the pipeline.

Quick check

Quick check: In which direction do loaders execute in the 'use' array?

  • Right to left
  • Left to right
  • Random order
Answer

Right to left — Loaders execute from right to left, so the rightmost loader runs first and passes output to the next loader.