Max RozenMax Rozen
TwitterArticlesNewsletter

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

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',
        ],
      },
    ],
  },
};

Do you struggle to keep up with best practices in React?

I send a single email weekly with an article like this one to help improve the quality of your React apps. Lots of developers like them, and I'd love to hear what you think as well. You can always unsubscribe.

    Join 43 React developers who signed up last week!

    rssTwitterGitHub

    © 2020 Max Rozen. All rights reserved.