Published on

Understanding Loaders in Webpack: Examples with Babel, CSS, and SASS Loaders

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

What Are Loaders in Webpack?

Loaders in Webpack are modules that preprocess files as they are bundled. They allow you to transform files like JavaScript, CSS, or images into a format that Webpack can process and include in your final build.

Some common use cases for loaders include:

  • Transpiling modern JavaScript to ES5 using Babel.
  • Processing and bundling CSS and SASS files.
  • Optimizing images for the web.

Using Babel Loader

The Babel loader transpiles modern JavaScript into a version compatible with older browsers.

Step 1: Install Dependencies

npm install --save-dev babel-loader @babel/core @babel/preset-env

Step 2: Configure Babel Loader

Update a property module in webpack.config.js, example is a below:

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

Step 3: Add Sample JavaScript

Create a src/index.js file:

const greet = () => {
  console.log('Hello, modern JavaScript!');
};

greet();

Run Webpack to see the transpiled code:

npx webpack

Example 2: Using CSS and SASS Loaders

CSS and SASS loaders allow you to bundle stylesheets directly into your application.

Step 1: Install Dependencies

npm install --save-dev style-loader css-loader sass-loader sass

Step 2: Configure CSS and SASS Loaders

Update webpack.config.js:

module.exports = {
  ...,
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
    ],
  },
};

Step 3: Add Sample Styles

Create a src/styles.scss file:

$bg-color: lightblue;

body {
  background-color: $bg-color;
  font-family: Arial, sans-serif;
}

Import the SASS file in src/index.js:

import './styles.scss';

console.log('Styles are loaded!');

Run Webpack to bundle your styles:

npx webpack

Open the dist/index.html file to see your styled page.


Conclusion

Webpack loaders provide a flexible way to preprocess and bundle various types of files in your project. By using loaders like Babel, CSS, and SASS, you can streamline your development workflow and ensure your application is optimized for the web.