PerfBeacon Logo
Sign inSign up

What is the difference between style-loader and mini-css-extract-plugin?

Max Rozen

style-loader

style-loader takes CSS you've imported in your JavaScript files, and injects them as <style></style> tags into the DOM. It's particularly useful for inlining Critical CSS into the <head> of your page.

If you decide to self-host your fonts instead of using Google Fonts, style-loader can also help you inline your font declarations so the browser knows immediately what to do with the font files it downloads.

How do you use style-loader?

/* style.css */
body {
  background: green;
}
/* component.js */
import './style.css';
/* webpack.config.js */
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};

mini-css-extract-plugin

mini-css-extract-plugin on the other hand, extracts your CSS into separate files.

It generates a CSS file for each JS file that imports CSS. It's more useful for CSS that you want to load asynchronously.

How do you use mini-css-extract-plugin?

/* webpack.config.js */
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Enjoyed this post? Receive the next one in your inbox!

Product

  • Features

Company

TwitterGitHub

© 2019-2020 Max Rozen. All rights reserved.