npm explorer

mini-css-extract-plugin

v2.10.0TypeScript

extracts CSS into separate files

webpackcssextracthmr
15.6M/weekUpdated 3 weeks agoMITUnpacked: 140.0 KB
Published by Tobias Koppers @sokra
npm install mini-css-extract-plugin
RepositoryHomepagenpm






mini-css-extract-plugin


[![npm][npm]][npm-url]
[![node][node]][node-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![discussion][discussion]][discussion-url]
[![size][size]][size-url]

mini-css-extract-plugin

This plugin extracts CSS into separate files. It creates a CSS file for each JS file that contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.

It builds on top of a new webpack v5 feature and requires webpack 5 to work.

Compared to the extract-text-webpack-plugin:

- Async loading
- No duplicate compilation (performance)
- Easier to use
- Specific to CSS

Getting Started

To begin, you'll need to install mini-css-extract-plugin:

``console
npm install --save-dev mini-css-extract-plugin
`

or

`console
yarn add -D mini-css-extract-plugin
`

or

`console
pnpm add -D mini-css-extract-plugin
`

It's recommended to combine mini-css-extract-plugin with the css-loader

Then add the loader and the plugin to your webpack configuration. For example:

style.css

`css
body {
background: green;
}
`

component.js

`js
import "./style.css";
`

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

> [!WARNING]
>
> Note that if you import CSS from your webpack entrypoint or import styles in the initial chunk,
mini-css-extract-plugin will not load this CSS into the page automatically. Please use html-webpack-plugin for automatic generation link tags or manually include a tag in your index.html file.

> [!WARNING]
>
> Source maps works only for
source-map/nosources-source-map/hidden-nosources-source-map/hidden-source-map values because CSS only supports source maps with the sourceMappingURL comment (i.e. //# sourceMappingURL=style.css.map). If you need set devtool to another value you can enable source maps generation for extracted CSS using sourceMap: true for css-loader.

Options

$3

- filename
-
chunkFilename
-
ignoreOrder
-
insert
-
attributes
-
linkType
-
runtime
-
experimentalUseImportModule

#### filename

Type:

`ts
type filename =
| string
| ((pathData: PathData, assetInfo?: AssetInfo) => string);
`

Default: [name].css

This option determines the name of each output CSS file.

Works like output.filename

#### chunkFilename

Type:

`ts
type chunkFilename =
| string
| ((pathData: PathData, assetInfo?: AssetInfo) => string);
`

Default: Based on filename

> Specifying chunkFilename as a function is only available in webpack@5

This option determines the name of non-entry chunk files.

Works like output.chunkFilename

#### ignoreOrder

Type:

`ts
type ignoreOrder = boolean;
`

Default: false

Remove Order Warnings.
See examples for more details.

#### insert

Type:

`ts
type insert = string | ((linkTag: HTMLLinkElement) => void);
`

Default: document.head.appendChild(linkTag);

Inserts the link tag at the given position for non-initial (async) CSS chunks

> [!WARNING]
>
> Only applicable for non-initial (async) chunks.

By default, the mini-css-extract-plugin appends styles ( elements) to document.head of the current window.

However in some circumstances it might be necessary to have finer control over the append target or even delay link elements insertion.
For example this is the case when you asynchronously load styles for an application that runs inside of an iframe.
In such cases
insert can be configured to be a function or a custom selector.

If you target an iframe, make sure that the parent document has sufficient access rights to reach into the frame document and append elements to it.

##### string

Allows to setup custom query selector.
A new
element will be inserted after the found item.

webpack.config.js

`js
new MiniCssExtractPlugin({
insert: "#some-element",
});
`

A new tag will be inserted after the element with the ID some-element.

##### function

Allows to override default behavior and insert styles at any position.

> ⚠ Do not forget that this code will run in the browser alongside your application. Since not all browsers support latest ECMA features like let, const, arrow function expression and etc we recommend you to use only ECMA 5 features and syntax.
>
> > ⚠ The
insert function is serialized to string and passed to the plugin. This means that it won't have access to the scope of the webpack configuration module.

webpack.config.js

`js
new MiniCssExtractPlugin({
insert(linkTag) {
const reference = document.querySelector("#some-element");
if (reference) {
reference.parentNode.insertBefore(linkTag, reference);
}
},
});
`

A new tag will be inserted before the element with the ID some-element.

#### attributes

Type:

`ts
type attributes = Record;
`

Default: {}

> [!WARNING]
>
> Only applies to non-initial (async) chunks.

If defined, the mini-css-extract-plugin will attach given attributes with their values on element.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
attributes: {
id: "target",
"data-target": "example",
},
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

> [!NOTE]
>
> It's only applied to dynamically loaded CSS chunks.
> If you want to modify
attributes inside HTML file, please use html-webpack-plugin

#### linkType

Type:

`ts
type linkType = string | boolean;
`

Default: text/css

This option allows loading asynchronous chunks with a custom link type, such as .

##### string

Possible values: text/css

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
linkType: "text/css",
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

##### boolean

false disables the link type attribute entirely.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
linkType: false,
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

#### runtime

Type:

`ts
type runtime = boolean;
`

Default: true

Allows to enable/disable the runtime generation.
CSS will be still extracted and can be used for a custom loading methods.
For example, you can use assets-webpack-plugin to retrieve them then use your own runtime code to download assets when needed.

false to skip.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
runtime: false,
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

#### experimentalUseImportModule

Type:

`ts
type experimentalUseImportModule = boolean;
`

Default: undefined

Enabled by default if not explicitly enabled (i.e. true and false allow you to explicitly control this option) and new API is available (at least webpack 5.52.0 is required).
Boolean values are available since version
5.33.2, but you need to enable experiments.executeModule (not required from webpack 5.52.0).

Use a new webpack API to execute modules instead of child compilers, significantly improving performance and memory usage.

When combined with experiments.layers, this adds a layer option to the loader options to specify the layer of the CSS execution.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
// You don't need this for
>= 5.52.0 due to the fact that this is enabled by default
// Required only for
>= 5.33.2 & <= 5.52.0
// Not available/unsafe for
<= 5.33.2
experimentalUseImportModule: true,
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
`

$3

- publicPath
-
emit
-
esModule
-
defaultExport

#### publicPath

Type:

`ts
type publicPath =
| string
| ((resourcePath: string, rootContext: string) => string);
`

Default: the publicPath in webpackOptions.output

Specifies a custom public path for the external resources like images, files, etc inside CSS.
Works like
output.publicPath

##### string

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "/public/path/to/",
},
},
"css-loader",
],
},
],
},
};
`

##### function

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) =>
${path.relative(path.dirname(resourcePath), context)}/,
},
},
"css-loader",
],
},
],
},
};
`

#### emit

Type:

`ts
type emit = boolean;
`

Default: true

If true, emits a file (writes a file to the filesystem).
If
false, the plugin will extract the CSS but will not emit the file.
It is often useful to disable this option for server-side packages.

#### esModule

Type:

`ts
type esModule = boolean;
`

Default: true

By default, mini-css-extract-plugin generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

You can enable a CommonJS syntax using:

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
esModule: false,
},
},
"css-loader",
],
},
],
},
};
`

#### defaultExport

Type:

`ts
type defaultExport = boolean;
`

Default: false

> [!NOTE]
>
> This option will work only when you set
namedExport to true in css-loader

By default, mini-css-extract-plugin generates JS modules based on the esModule and namedExport options in css-loader.
Using the
esModule and namedExport options will allow you to better optimize your code.
If you set
esModule: true and namedExport: true for css-loader mini-css-extract-plugin will generate only a named export.
Our official recommendation is to use only named export for better future compatibility.
But for some applications, it is not easy to quickly rewrite the code from the default export to a named export.

In case you need both default and named exports, you can enable this option:

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
defaultExport: true,
},
},
{
loader: "css-loader",
options: {
esModule: true,
modules: {
namedExport: true,
},
},
},
],
},
],
},
};
`

Examples

$3

For production builds, it is recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on. This can be achieved by using the mini-css-extract-plugin, because it creates separate css files.
For
development mode (including webpack-dev-server) you can use style-loader, because it injects CSS into the DOM using multiple and works faster.

> Important: Do not use style-loader and mini-css-extract-plugin together.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const devMode = process.env.NODE_ENV !== "production";

module.exports = {
module: {
rules: [
{
// If you enable
experiments.css or experiments.futureDefaults, please uncomment line below
// type: "javascript/auto",
test: /\.(sa|sc|c)ss$/,
use: [
devMode ? "style-loader" : MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
plugins: [devMode ? [] : [new MiniCssExtractPlugin()]].flat(),
};
`

$3

webpack.config.js

`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: "../",
},
},
"css-loader",
],
},
],
},
};
`

$3

> ⚠ Names of locals are converted to camelCase.

> ⚠ It is not allowed to use JavaScript reserved words in CSS class names.

> ⚠ Options esModule and modules.namedExport in css-loader should be enabled.

styles.css

`css
.foo-baz {
color: red;
}
.bar {
color: blue;
}
`

index.js

`js
import { bar, fooBaz } from "./styles.css";

console.log(fooBaz, bar);
`

You can enable a ES module named export using:

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: "css-loader",
options: {
esModule: true,
modules: {
namedExport: true,
localIdentName: "foo__[name]__[local]",
},
},
},
],
},
],
},
};
`

$3

You can specify publicPath as a function to dynamically determine the public path based on each resource’s location relative to the project root or context.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) =>
// publicPath is the relative path of the resource to the context
// e.g. for ./css/admin/main.css the publicPath will be ../../
// while for ./css/main.css the publicPath will be ../
${path.relative(path.dirname(resourcePath), context)}/,
},
},
"css-loader",
],
},
],
},
};
`

$3

This plugin should not be used with style-loader in the loaders chain.

Here is an example to have both HMR in development and your styles extracted in a file for production builds.

(Loaders options left out for clarity, adapt accordingly to your needs.)

You should not use HotModuleReplacementPlugin plugin if you are using a webpack-dev-server.
webpack-dev-server enables / disables HMR using hot option.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");

const devMode = process.env.NODE_ENV !== "production";

const plugins = [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: devMode ? "[name].css" : "[name].[contenthash].css",
chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css",
}),
];
if (devMode) {
// only enable hot in development
plugins.push(new webpack.HotModuleReplacementPlugin());
}

module.exports = {
plugins,
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
};
`

$3

> [!NOTE]
>
> HMR is automatically supported in webpack 5. No need to configure it. Skip the following:

The mini-css-extract-plugin supports hot reloading of actual CSS files in development.
Some options are provided to enable HMR of both standard stylesheets and locally scoped CSS or CSS modules.
Below is an example configuration of mini-css for HMR use with CSS modules.

You should not use HotModuleReplacementPlugin plugin if you are using a webpack-dev-server.
webpack-dev-server enables / disables HMR using hot option.

webpack.config.js

`js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");

const plugins = [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: devMode ? "[name].css" : "[name].[contenthash].css",
chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css",
}),
];
if (devMode) {
// only enable hot in development
plugins.push(new webpack.HotModuleReplacementPlugin());
}

module.exports = {
plugins,
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {},
},
"css-loader",
],
},
],
},
};
`

$3

To minify the output, use a plugin like css-minimizer-webpack-plugin.

webpack.config.js

`js
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
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"],
},
],
},
optimization: {
minimizer: [
// For webpack@5 you can use the
... syntax to extend existing minimizers (i.e. terser-webpack-plugin).
// Uncomment the next line o keep JS minimizers and add CSS minimizer:
//
...,
new CssMinimizerPlugin(),
],
},
};
`

- By default, CSS minimization runs in production mode.
- If you want to run it also in development set the
optimization.minimize option to true.

$3

The runtime code detects already added CSS via or