SkillByAIOpen interactive version →

Lesson 4 / 25

Loaders and rules

Use Webpack loaders and module rules to process CSS and modern JavaScript, and learn why loader order matters.

What loaders do

Webpack natively understands only JavaScript and JSON. Loaders transform other file types into valid modules. They match files with a pattern (test) and apply transformations (use). Common loaders include babel-loader for JavaScript transpilation and css-loader with style-loader for CSS. For images and fonts, use Webpack 5 asset modules instead of file-loader.

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
  • Alphabetical order
Answer

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