Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Lightweight CSS extraction plugin

License

NotificationsYou must be signed in to change notification settings

webpack-contrib/mini-css-extract-plugin

Repository files navigation

mini-css-extract-plugin

npmnodetestscoveragediscussionsize

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 installmini-css-extract-plugin:

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

or

yarn add -D mini-css-extract-plugin

or

pnpm add -D mini-css-extract-plugin

It's recommended to combinemini-css-extract-plugin with thecss-loader

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

style.css

body {background: green;}

component.js

import"./style.css";

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin()],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 theinitial chunk,mini-css-extract-plugin will not load this CSS into the page automatically. Please usehtml-webpack-plugin for automatic generationlink tags or manually include a<link> tag in yourindex.html file.

Warning

Source maps works only forsource-map/nosources-source-map/hidden-nosources-source-map/hidden-source-map values because CSS only supports source maps with thesourceMappingURL comment (i.e.//# sourceMappingURL=style.css.map). If you need setdevtool to another value you can enable source maps generation for extracted CSS usingsourceMap: true forcss-loader.

Options

Plugin Options

filename

Type:

typefilename=|string|((pathData:PathData,assetInfo?:AssetInfo)=>string);

Default:[name].css

This option determines the name of each output CSS file.

Works likeoutput.filename

chunkFilename

Type:

typechunkFilename=|string|((pathData:PathData,assetInfo?:AssetInfo)=>string);

Default:Based on filename

SpecifyingchunkFilename as afunction is only available in webpack@5

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

Works likeoutput.chunkFilename

ignoreOrder

Type:

typeignoreOrder=boolean;

Default:false

Remove Order Warnings.Seeexamples for more details.

insert

Type:

typeinsert=string|((linkTag:HTMLLinkElement)=>void);

Default:document.head.appendChild(linkTag);

Inserts thelink tag at the given position fornon-initial (async) CSS chunks

Warning

Only applicable fornon-initial (async) chunks.

By default, themini-css-extract-plugin appends styles (<link> elements) todocument.head of the currentwindow.

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

If you target aniframe, 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 customquery selector.A new<link> element will be inserted after the found item.

webpack.config.js

newMiniCssExtractPlugin({insert:"#some-element",});

A new<link> tag will be inserted after the element with the IDsome-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 likelet,const,arrow function expression and etc we recommend you to use only ECMA 5 features and syntax.

⚠ Theinsert 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

newMiniCssExtractPlugin({insert:function(linkTag){varreference=document.querySelector("#some-element");if(reference){reference.parentNode.insertBefore(linkTag,reference);}},});

A new<link> tag will be inserted before the element with the IDsome-element.

attributes

Type:

typeattributes=Record<string,string>};

Default:{}

Warning

Only applies tonon-initial (async) chunks.

If defined, themini-css-extract-plugin will attach given attributes with their values on<link> element.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({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<link> attributes inside HTML file, please usehtml-webpack-plugin

linkType

Type:

typelinkType=string|boolean;

Default:text/css

This option allows loading asynchronous chunks with a custom link type, such as<link type="text/css" ...>.

string

Possible values:text/css

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({linkType:"text/css",}),],module:{rules:[{test:/\.css$/i,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};
boolean

false disables the linktype attribute entirely.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({linkType:false,}),],module:{rules:[{test:/\.css$/i,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

runtime

Type:

typeruntime=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 useassets-webpack-plugin to retrieve them then use your own runtime code to download assets when needed.

false to skip.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({runtime:false,}),],module:{rules:[{test:/\.css$/i,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

experimentalUseImportModule

Type:

typeexperimentalUseImportModule=boolean;

Default:undefined

Enabled by default if not explicitly enabled (i.e.true andfalse allow you to explicitly control this option) and new API is available (at least webpack5.52.0 is required).Boolean values are available since version5.33.2, but you need to enableexperiments.executeModule (not required from webpack5.52.0).

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

When combined withexperiments.layers, this adds alayer option to the loader options to specify the layer of the CSS execution.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({// 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"],},],},};

Loader Options

publicPath

Type:

typepublicPath=|string|((resourcePath:string,rootContext:string)=>string);

Default: thepublicPath inwebpackOptions.output

Specifies a custom public path for the external resources like images, files, etc insideCSS.Works likeoutput.publicPath

string

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// both options are optionalfilename:"[name].css",chunkFilename:"[id].css",}),],module:{rules:[{test:/\.css$/,use:[{loader:MiniCssExtractPlugin.loader,options:{publicPath:"/public/path/to/",},},"css-loader",],},],},};
function

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// both options are optionalfilename:"[name].css",chunkFilename:"[id].css",}),],module:{rules:[{test:/\.css$/,use:[{loader:MiniCssExtractPlugin.loader,options:{publicPath:(resourcePath,context)=>{returnpath.relative(path.dirname(resourcePath),context)+"/";},},},"css-loader",],},],},};

emit

Type:

typeemit=boolean;

Default:true

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

esModule

Type:

typeesModule=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 ofmodule concatenation andtree shaking.

You can enable a CommonJS syntax using:

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin()],module:{rules:[{test:/\.css$/i,use:[{loader:MiniCssExtractPlugin.loader,options:{esModule:false,},},"css-loader",],},],},};

defaultExport

Type:

typedefaultExport=boolean;

Default:false

Note

This option will work only when you setnamedExport totrue incss-loader

By default,mini-css-extract-plugin generates JS modules based on theesModule andnamedExport options incss-loader.Using theesModule andnamedExport options will allow you to better optimize your code.If you setesModule: true andnamedExport: true forcss-loadermini-css-extract-plugin will generateonly 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

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

Examples

Recommended

Forproduction 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 themini-css-extract-plugin, because it creates separate css files.Fordevelopment mode (includingwebpack-dev-server) you can usestyle-loader, because it injects CSS into the DOM using multiple <style></style> and works faster.

Important: Do not usestyle-loader andmini-css-extract-plugin together.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");constdevMode=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:[].concat(devMode ?[] :[newMiniCssExtractPlugin()]),};

Minimal example

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// all options are optionalfilename:"[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.outputpublicPath:"../",},},"css-loader",],},],},};

Named export for CSS Modules

⚠ Names of locals are converted tocamelCase.

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

⚠ OptionsesModule andmodules.namedExport incss-loader should be enabled.

styles.css

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

index.js

import{fooBaz,bar}from"./styles.css";console.log(fooBaz,bar);

You can enable a ES module named export using:

webpack.config.js

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

ThepublicPath option as function

You can specifypublicPath 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

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// both options are optionalfilename:"[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 ../returnpath.relative(path.dirname(resourcePath),context)+"/";},},},"css-loader",],},],},};

Advanced configuration example

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

Here is an example to have both HMR indevelopment and your styles extracted in a file forproduction builds.

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

You should not useHotModuleReplacementPlugin plugin if you are using awebpack-dev-server.webpack-dev-server enables / disables HMR usinghot option.

webpack.config.js

constwebpack=require("webpack");constMiniCssExtractPlugin=require("mini-css-extract-plugin");constdevMode=process.env.NODE_ENV!=="production";constplugins=[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// both options are optionalfilename:devMode ?"[name].css" :"[name].[contenthash].css",chunkFilename:devMode ?"[id].css" :"[id].[contenthash].css",}),];if(devMode){// only enable hot in developmentplugins.push(newwebpack.HotModuleReplacementPlugin());}module.exports={  plugins,module:{rules:[{test:/\.(sa|sc|c)ss$/,use:[MiniCssExtractPlugin.loader,"css-loader","postcss-loader","sass-loader",],},],},};

Hot Module Reloading (HMR)

Note

HMR is automatically supported in webpack 5. No need to configure it. Skip the following:

Themini-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 useHotModuleReplacementPlugin plugin if you are using awebpack-dev-server.webpack-dev-server enables / disables HMR usinghot option.

webpack.config.js

constwebpack=require("webpack");constMiniCssExtractPlugin=require("mini-css-extract-plugin");constplugins=[newMiniCssExtractPlugin({// Options similar to the same options in webpackOptions.output// both options are optionalfilename:devMode ?"[name].css" :"[name].[contenthash].css",chunkFilename:devMode ?"[id].css" :"[id].[contenthash].css",}),];if(devMode){// only enable hot in developmentplugins.push(newwebpack.HotModuleReplacementPlugin());}module.exports={  plugins,module:{rules:[{test:/\.css$/,use:[{loader:MiniCssExtractPlugin.loader,options:{},},"css-loader",],},],},};

Minimizing For Production

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

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");constCssMinimizerPlugin=require("css-minimizer-webpack-plugin");module.exports={plugins:[newMiniCssExtractPlugin({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:// `...`,newCssMinimizerPlugin(),],},};
  • By default, CSS minimization runs in production mode.
  • If you want to run it also in development set theoptimization.minimize option totrue.

Using preloaded or inlined CSS

The runtime code detects already added CSS via<link> or<style> tags and avoids duplicating CSS loading.

  • This can be useful when injecting CSS on server-side for Server-Side-Rendering (SSR).
  • Thehref of the<link> tag has to match the URL that will be used for loading the CSS chunk.
  • Thedata-href attribute can be used for both<link> and<style> elements.
  • When inlining CSSdata-href must be used.

Extracting all CSS in a single file

The CSS can be extracted in one CSS file usingoptimization.splitChunks.cacheGroups with thetype"css/mini-extract".

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={optimization:{splitChunks:{cacheGroups:{styles:{name:"styles",type:"css/mini-extract",chunks:"all",enforce:true,},},},},plugins:[newMiniCssExtractPlugin({filename:"[name].css",}),],module:{rules:[{test:/\.css$/,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

Note thattype should be used instead oftest in Webpack 5, or else an extra.js file can be generated besides the.css file. This is becausetest doesn't know which modules should be dropped (in this case, it won't detect that.js should be dropped).

Extracting CSS based on entry

You may also extract the CSS based on the webpack entry name.This is especially useful if you import routes dynamically but want to keep your CSS bundled according to entry.This also prevents the CSS duplication issue one had with the ExtractTextPlugin.

constpath=require("path");constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={entry:{foo:path.resolve(__dirname,"src/foo"),bar:path.resolve(__dirname,"src/bar"),},optimization:{splitChunks:{cacheGroups:{fooStyles:{type:"css/mini-extract",name:"styles_foo",chunks:(chunk)=>{returnchunk.name==="foo";},enforce:true,},barStyles:{type:"css/mini-extract",name:"styles_bar",chunks:(chunk)=>{returnchunk.name==="bar";},enforce:true,},},},},plugins:[newMiniCssExtractPlugin({filename:"[name].css",}),],module:{rules:[{test:/\.css$/,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

Filename Option as function

With thefilename option you can use chunk data to customize the filename.This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk.In the example below, we'll usefilename to output the generated css into a different directory.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({filename:({ chunk})=>`${chunk.name.replace("/js/","/css/")}.css`,}),],module:{rules:[{test:/\.css$/,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

Long Term Caching

For long term caching usefilename: "[contenthash].css". Optionally add[name].

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({filename:"[name].[contenthash].css",chunkFilename:"[id].[contenthash].css",}),],module:{rules:[{test:/\.css$/,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

Remove Order Warnings

For projects where CSS ordering has been mitigated through consistent use of scoping or naming conventions, such asCSS Modules, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={plugins:[newMiniCssExtractPlugin({ignoreOrder:true,}),],module:{rules:[{test:/\.css$/i,use:[MiniCssExtractPlugin.loader,"css-loader"],},],},};

Multiple Themes

Switch themes by conditionally loading different SCSS variants with query parameters.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");module.exports={entry:"./src/index.js",module:{rules:[{test:/\.s[ac]ss$/i,oneOf:[{resourceQuery:"?dark",use:[MiniCssExtractPlugin.loader,"css-loader",{loader:"sass-loader",options:{additionalData:`@use 'dark-theme/vars' as vars;`,},},],},{use:[MiniCssExtractPlugin.loader,"css-loader",{loader:"sass-loader",options:{additionalData:`@use 'light-theme/vars' as vars;`,},},],},],},],},plugins:[newMiniCssExtractPlugin({filename:"[name].css",attributes:{id:"theme",},}),],};

src/index.js

import"./style.scss";lettheme="light";constthemes={};themes[theme]=document.querySelector("#theme");asyncfunctionloadTheme(newTheme){// eslint-disable-next-line no-consoleconsole.log(`CHANGE THEME -${newTheme}`);constthemeElement=document.querySelector("#theme");if(themeElement){themeElement.remove();}if(themes[newTheme]){// eslint-disable-next-line no-consoleconsole.log(`THEME ALREADY LOADED -${newTheme}`);document.head.appendChild(themes[newTheme]);return;}if(newTheme==="dark"){// eslint-disable-next-line no-consoleconsole.log(`LOADING THEME -${newTheme}`);import(/* webpackChunkName: "dark" */"./style.scss?dark").then(()=>{themes[newTheme]=document.querySelector("#theme");// eslint-disable-next-line no-consoleconsole.log(`LOADED -${newTheme}`);});}}document.onclick=()=>{if(theme==="light"){theme="dark";}else{theme="light";}loadTheme(theme);};

src/dark-theme/_vars.scss

$background:black;

src/light-theme/_vars.scss

$background:white;

src/styles.scss

body {background-color:vars.$background;}

public/index.html

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1"/><title>Document</title><linkid="theme"rel="stylesheet"type="text/css"href="./main.css"/></head><body><scriptsrc="./main.js"></script></body></html>

Media Query Plugin

If you'd like to extract the media queries from the extracted CSS (so mobile users don't need to load desktop or tablet specific CSS anymore) you should use one of the following plugins:

Hooks

The mini-css-extract-plugin provides hooks to extend it to your needs.

beforeTagInsert

SyncWaterfallHook

Called before inject the insert code for link tag. Should return a string

MiniCssExtractPlugin.getCompilationHooks(compilation).beforeTagInsert.tap("changeHref",(source,varNames)=>Template.asString([source,`${varNames.tag}.setAttribute("href", "https://github.com/webpack-contrib/mini-css-extract-plugin");`,]));

Contributing

We welcome all contributions!If you're new here, please take a moment to review our contributing guidelines before submitting issues or pull requests.

CONTRIBUTING

License

MIT

About

Lightweight CSS extraction plugin

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Languages


    [8]ページ先頭

    ©2009-2025 Movatter.jp