gitmyhub

mini-css-extract-plugin

JavaScript ★ 4.7k updated 2mo ago

Lightweight CSS extraction plugin

This is a plugin for webpack, a tool that bundles JavaScript files together for use in a browser. Specifically, mini-css-extract-plugin handles CSS files inside that bundling process. When you write a web app and import CSS styles directly inside your JavaScript code, this plugin pulls those styles out into separate CSS files instead of mixing everything into one big bundle.

The practical result is that your site can load CSS files on their own, independently of the JavaScript. This matters for page speed because the browser can download CSS and JavaScript in parallel, and it can cache the CSS file separately so returning visitors do not re-download styles that have not changed. The plugin also supports loading CSS files on demand, meaning styles for a page section you have not visited yet stay unloaded until you need them.

Setting it up requires two pieces: the plugin itself, which you add to the plugins section of your webpack configuration, and a loader, which you add to the rules that tell webpack how to handle .css files. You install both with a single npm, yarn, or pnpm command. The README includes working code examples showing the exact configuration shape.

There are several options you can tune. You can control the output filename pattern for CSS files, add custom HTML attributes to the link tags the plugin inserts, change where in the document those link tags get placed, or disable the link type attribute entirely. One option called ignoreOrder suppresses warnings that appear when the order CSS gets loaded might vary between pages.

One thing to know upfront: the plugin does not automatically inject a link tag into your HTML for CSS that comes from your main entry point. For that, you either add the link tag by hand in your HTML file or use a companion plugin called html-webpack-plugin. This plugin requires webpack version 5 and does not work with older versions.