icon-pwa-512x512.d3dae4189855b3a72ff9.png

Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!

Example

For example, you can use loaders to tell webpack to load a CSS file or to convert TypeScript to JavaScript. To do this, you would start by installing the loaders you need:

npm install --save-dev css-loader ts-loader

And then instruct webpack to use the css-loader for every .css file and the ts-loader for all .ts files:

webpack.config.js

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

Using Loaders

There are two ways to use loaders in your application:

Configuration

module.rules allows you to specify several loaders within your webpack configuration. This is a concise way to display loaders, and helps to maintain clean code. It also offers you a full overview of each respective loader.

Loaders are evaluated/executed from right to left (or from bottom to top). In the example below execution starts with sass-loader, continues with css-loader and finally ends with style-loader. See "Loader Features" for more information about loaders order.

module.exports = {
  module: {
    rules: [
      {
        test: /\\.css$/,
        use: [
          // [style-loader](/loaders/style-loader)
          { loader: 'style-loader' },
          // [css-loader](/loaders/css-loader)
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          },
          // [sass-loader](/loaders/sass-loader)
          { loader: 'sass-loader' }
        ]
      }
    ]
  }
};

Inline

It's possible to specify loaders in an import statement, or any equivalent "importing" method. Separate loaders from the resource with !. Each part is resolved relative to the current directory.

import Styles from 'style-loader!css-loader?modules!./styles.css';

It's possible to override any loaders, preLoaders and postLoaders from the configuration by prefixing the inline import statement: