Loaders in Webpack

Webpack also uses loaders to extend its capabilities. They allow you to take files of a certain type and perform certain operations on them.

For example, you can take all files with the extension .less, convert their text to CSS, then minify the resulting CSS and save it in one common file.

Let's look at the general scheme of working with a loader using two imaginary loaders as an example.

Let's install the first loader:

terminalnpm install test-loader1 --save-dev

Let's install the second loader:

terminalnpm install test-loader2 --save-dev

After installing the loaders, we can use them in the configuration file (they don't need to be imported). See the syntax:

webpack.config.jsexport default {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.css$/i, // file type use: ['test-loader1', 'test-loader2'], // loaders
      },
    ],
  },
};

You can write the array elements not in a row, but in a column:

webpack.config.jsexport default {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          'test-loader1',
          'test-loader2'
        ],
      },
    ],
  },
};

You can write different rules for different file types:

webpack.config.jsexport default {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.sass$/i,
        use: [
          'test-loader1',
          'test-loader2'
        ],
      },
      {
        test: /\.less$/i,
        use: [
          'test-loader3',
          'test-loader4'
        ],
      },
    ],
  },
};

Loaders are executed in turn. The queue starts from the end of the array. That is, the loader specified by the last element of the array is executed first, then the next to last one, and so on.