What is mini-css-extract-plugin?
The mini-css-extract-plugin is a plugin for webpack that extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports on-demand-loading of CSS and SourceMaps. It requires webpack 4 to function.
What are mini-css-extract-plugin's main functionalities?
Extract CSS into separate files
This feature allows you to extract CSS from your bundle into a separate file, which can be loaded independently.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
})
]
};
Lazy loading of CSS files
This feature enables on-demand loading of CSS by splitting the CSS into chunks and loading them when needed.
import(/* webpackChunkName: 'style' */ './style.css').then(() => {
// Use style.css
});
SourceMap support
This feature allows you to generate source maps for the CSS files, which is helpful for debugging purposes.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
sourceMap: true
}
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
})
]
};
Other packages similar to mini-css-extract-plugin
extract-text-webpack-plugin
This package is similar to mini-css-extract-plugin but was used for webpack 3 and earlier. It is now deprecated in favor of mini-css-extract-plugin, which is designed for webpack 4 and later.
style-loader
This package injects CSS into the DOM using multiple <style> tags. It is often used in development environments for hot module replacement but does not extract CSS into separate files.
sass-loader
While sass-loader itself does not extract CSS, it is commonly used in conjunction with mini-css-extract-plugin to compile Sass/SCSS files into CSS and then extract it into separate files.
desc
This plugin extract CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.
It builds on top of a new webpack v4 feature (module types) and requires webpack 4 to work.
Compared to the extract-text-webpack-plugin:
- Async loading
- No duplicate compilation (performance)
- Easier to use
- Specific to CSS
TODO:
Install
npm install --save-dev mini-css-extract-plugin
Usage
Configuration
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
]
}
}
Maintainers