此外掛程式將 CSS 提取到個別檔案中。它會為包含 CSS 的每個 JS 檔案建立一個 CSS 檔案。它支援 CSS 的隨選載入和原始碼對應。
它建立在 webpack v5 的新功能之上,並且需要 webpack 5 才能運作。
與 extract-text-webpack-plugin 相比
首先,您需要安裝 mini-css-extract-plugin
npm install --save-dev mini-css-extract-plugin
或
yarn add -D mini-css-extract-plugin
或
pnpm add -D mini-css-extract-plugin
建議將 mini-css-extract-plugin
與 css-loader
結合使用
然後將載入器和外掛程式新增到您的 webpack
設定檔中。例如
style.css
body {
background: green;
}
component.js
import "./style.css";
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
警告
請注意,如果您從 webpack 進入點匯入 CSS 或在 初始 區塊中匯入樣式,
mini-css-extract-plugin
將不會將此 CSS 載入到頁面中。請使用html-webpack-plugin
自動產生link
標籤,或建立包含link
標籤的index.html
檔案。
警告
原始碼對應僅適用於
source-map
/nosources-source-map
/hidden-nosources-source-map
/hidden-source-map
值,因為 CSS 僅支援帶有sourceMappingURL
註解的原始碼對應(即//# sourceMappingURL=style.css.map
)。如果您需要將devtool
設定為其他值,您可以使用sourceMap: true
為css-loader
啟用提取 CSS 的原始碼對應產生。
filename
類型
type filename =
| string
| ((pathData: PathData, assetInfo?: AssetInfo) => string);
預設:[name].css
此選項決定每個輸出 CSS 檔案的名稱。
作用類似 output.filename
chunkFilename
類型
type chunkFilename =
| string
| ((pathData: PathData, assetInfo?: AssetInfo) => string);
預設:根據 filename
僅 webpack@5 可將
chunkFilename
設定為function
此選項決定非入口區塊檔案的名稱。
作用類似 output.chunkFilename
ignoreOrder
類型
type ignoreOrder = boolean;
預設:false
移除順序警告。有關詳細資訊,請參閱以下 範例。
insert
類型
type insert = string | ((linkTag: HTMLLinkElement) => void);
預設:document.head.appendChild(linkTag);
針對 非初始(非同步) CSS 區塊,在指定位置插入 link
標籤
警告
僅適用於 非初始(非同步) 區塊。
預設情況下,mini-css-extract-plugin
會將樣式(<link>
元素)附加到當前 window
的 document.head
。
然而,在某些情況下,可能需要對附加目標進行更精細的控制,甚至延遲插入 link
元素。例如,這是當您為在 iframe 內執行的應用程式非同步載入樣式時的情況。在這種情況下,insert
可以設定為函式或自訂選擇器。
如果您鎖定 iframe,請確保父文件具有足夠的存取權限來進入框架文件並附加元素到其中。
string
允許設定自訂 查詢選擇器。新的 <link>
元素將會在找到的項目後插入。
webpack.config.js
new MiniCssExtractPlugin({
insert: "#some-element",
});
新的 <link>
元素將會在 id 為 some-element
的元素後插入。
function
允許覆寫預設行為並在任何位置插入樣式。
⚠ 請不要忘記此程式碼將與您的應用程式一起在瀏覽器中執行。由於並非所有瀏覽器都支援最新的 ECMA 功能,例如
let
、const
、arrow function expression
等,我們建議您僅使用 ECMA 5 功能和語法。
insert
函式會序列化為字串並傳遞給外掛程式。這表示它無法存取 webpack 設定模組的範圍。
webpack.config.js
new MiniCssExtractPlugin({
insert: function (linkTag) {
var reference = document.querySelector("#some-element");
if (reference) {
reference.parentNode.insertBefore(linkTag, reference);
}
},
});
新的 <link>
元素將會在 id 為 some-element
的元素前插入。
attributes
類型
type attributes = Record<string, string>};
預設值:{}
警告
僅適用於 非初始(非同步) 區塊。
如果已定義,mini-css-extract-plugin
會在 <link>
元素上附加具有其值的給定屬性。
webpack.config.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"],
},
],
},
};
注意
它僅套用於動態載入的 css 區塊,如果你想修改 html 檔案中的連結屬性,請使用 html-webpack-plugin
linkType
類型
type linkType = string | boolean;
預設值:text/css
此選項允許使用自訂連結類型載入非同步區塊,例如 <link type="text/css" ...>
。
字串
可能值:text/css
webpack.config.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"],
},
],
},
};
布林值
false
會停用連結 type
屬性
webpack.config.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 runtime = boolean;
預設值:true
允許啟用/停用執行時間產生。CSS 仍會被萃取,且可用於自訂載入方法。例如,你可以使用 assets-webpack-plugin 來擷取它們,然後使用你自己的執行時間程式碼在需要時下載資源。
false
為略過。
webpack.config.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 experimentalUseImportModule = boolean;
預設值:未定義
如果未明確啟用(即 true
和 false
允許你明確控制此選項),且有新的 API 可用(至少需要 webpack 5.52.0
),則預設啟用。布林值自版本 5.33.2
起可用,但你需要啟用 experiments.executeModule
(從 webpack 5.52.0
起不需要)。
使用新的 webpack API 來執行模組,而不是子編譯器。這大幅改善了效能和記憶體使用量。
與 experiments.layers
結合使用時,這會在 loader 選項中新增一個 layer
選項,以指定 css 執行的層級。
webpack.config.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"],
},
],
},
};
publicPath
類型
type publicPath =
| string
| ((resourcePath: string, rootContext: string) => string);
預設:webpackOptions.output
中的 publicPath
指定 CSS
內部圖像、檔案等外部資源的客製化公共路徑。作用類似於 output.publicPath
字串
webpack.config.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",
],
},
],
},
};
函式
webpack.config.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) => {
return path.relative(path.dirname(resourcePath), context) + "/";
},
},
},
"css-loader",
],
},
],
},
};
emit
類型
type emit = boolean;
預設值:true
如果為 true,則發射檔案(將檔案寫入檔案系統)。如果為 false,外掛程式會擷取 CSS,但不會發射檔案。對於伺服器端套件,停用此選項通常很有用。
esModule
類型
type esModule = boolean;
預設值:true
預設情況下,mini-css-extract-plugin
會產生使用 ES 模組語法的 JS 模組。在某些情況下,使用 ES 模組是有益的,例如在 模組串接 和 樹狀搖晃 的情況下。
你可以使用以下方式啟用 CommonJS 語法
webpack.config.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",
],
},
],
},
};
對於 production
建置,建議從你的套件中擷取 CSS,以便稍後能夠並行載入 CSS/JS 資源。這可以使用 mini-css-extract-plugin
來達成,因為它會建立個別的 css 檔案。對於 development
模式(包括 webpack-dev-server
),你可以使用 style-loader,因為它會使用多個方式將 CSS 注入 DOM 且運作速度較快。
不要同時使用
style-loader
和mini-css-extract-plugin
。
webpack.config.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: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
};
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: "../",
},
},
"css-loader",
],
},
],
},
};
⚠ 本地變數名稱會轉換成
camelCase
。
⚠ 不允許在 CSS 類別名稱中使用 JavaScript 保留字。
css-loader
中的esModule
和modules.namedExport
選項應啟用。
styles.css
.foo-baz {
color: red;
}
.bar {
color: blue;
}
index.js
import { fooBaz, bar } from "./styles.css";
console.log(fooBaz, bar);
你可以使用以下方式啟用 ES 模組命名匯出
webpack.config.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]",
},
},
},
],
},
],
},
};
publicPath
選項作為函數webpack.config.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 ../
return path.relative(path.dirname(resourcePath), context) + "/";
},
},
},
"css-loader",
],
},
],
},
};
此外掛程式不應與載入器鏈中的 style-loader
一起使用。
以下是一個範例,說明如何在 development
中同時使用 HMR,並在 production
建置中將樣式萃取到一個檔案中。
(載入器選項省略以提高清晰度,請根據需要調整。)
如果你正在使用 webpack-dev-server
,則不應使用 HotModuleReplacementPlugin
外掛程式。webpack-dev-server
使用 hot
選項啟用 / 停用 HMR。
webpack.config.js
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
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",
],
},
],
},
};
注意
webpack 5 自動支援 HMR。無需組態它。略過以下
mini-css-extract-plugin
支援在開發中熱重新載入實際的 css 檔案。提供了一些選項來啟用標準樣式表和本地範圍的 CSS 或 CSS 模組的 HMR。以下是 mini-css 的範例組態,用於將 HMR 與 CSS 模組搭配使用。
如果你正在使用 webpack-dev-server
,則不應使用 HotModuleReplacementPlugin
外掛程式。webpack-dev-server
使用 hot
選項啟用 / 停用 HMR。
webpack.config.js
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
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",
],
},
],
},
};
若要縮小輸出,請使用外掛程式,例如 css-minimizer-webpack-plugin。
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-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
// `...`,
new CssMinimizerPlugin(),
],
},
};
這將僅在生產模式中啟用 CSS 最佳化。如果您想在開發中也執行此操作,請將 optimization.minimize
選項設定為 true。
執行時期程式碼會透過 <link>
或 <style>
標籤偵測已新增的 CSS。這在伺服器端注入 CSS 以進行伺服器端呈現時很有用。<link>
標籤的 href
必須與用於載入 CSS 區塊的 URL 相符。data-href
屬性也可同時用於 <link>
和 <style>
。在內嵌 CSS 時,必須使用 data-href
。
可以使用 optimization.splitChunks.cacheGroups
將 CSS 萃取到一個 CSS 檔案中。
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: "styles",
type: "css/mini-extract",
chunks: "all",
enforce: true,
},
},
},
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
請注意,在 Webpack 5 中應使用 type
取代 test
,否則除了 .css
檔案外,還可能會產生一個額外的 .js
檔案。這是因為 test
不知道應該捨棄哪些模組(在本例中,它不會偵測到應該捨棄 .js
)。
您也可以根據 webpack 入口名稱來提取 CSS。如果您動態匯入路由,但希望根據入口來將 CSS 捆綁在一起,這將特別有用。這還可以防止 ExtractTextPlugin 遇到的 CSS 重複問題。
const path = require("path");
const MiniCssExtractPlugin = 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) => {
return chunk.name === "foo";
},
enforce: true,
},
barStyles: {
type: "css/mini-extract",
name: "styles_bar",
chunks: (chunk) => {
return chunk.name === "bar";
},
enforce: true,
},
},
},
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
使用 filename
選項,您可以使用區塊資料自訂檔案名稱。這在處理多個入口點,並希望對特定入口點/區塊的檔案名稱有更多控制時特別有用。在以下範例中,我們將使用 filename
將產生的 CSS 輸出到不同的目錄。
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: ({ chunk }) => `${chunk.name.replace("/js/", "/css/")}.css`,
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
對於長期快取,請使用 filename: "[contenthash].css"
。選擇性地加入 [name]
。
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css",
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
對於透過一致使用範圍或命名慣例(例如 CSS 模組)來減輕 css 順序的專案,可以透過將 ignoreOrder 標記設定為 true 來停用 css 順序警告。
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
ignoreOrder: true,
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
};
webpack.config.js
const MiniCssExtractPlugin = 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: [
new MiniCssExtractPlugin({
filename: "[name].css",
attributes: {
id: "theme",
},
}),
],
};
src/index.js
import "./style.scss";
let theme = "light";
const themes = {};
themes[theme] = document.querySelector("#theme");
async function loadTheme(newTheme) {
// eslint-disable-next-line no-console
console.log(`CHANGE THEME - ${newTheme}`);
const themeElement = document.querySelector("#theme");
if (themeElement) {
themeElement.remove();
}
if (themes[newTheme]) {
// eslint-disable-next-line no-console
console.log(`THEME ALREADY LOADED - ${newTheme}`);
document.head.appendChild(themes[newTheme]);
return;
}
if (newTheme === "dark") {
// eslint-disable-next-line no-console
console.log(`LOADING THEME - ${newTheme}`);
import(/* webpackChunkName: "dark" */ "./style.scss?dark").then(() => {
themes[newTheme] = document.querySelector("#theme");
// eslint-disable-next-line no-console
console.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>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Document</title>
<link id="theme" rel="stylesheet" type="text/css" href="./main.css" />
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
如果您想從提取的 CSS 中提取媒體查詢(因此行動裝置使用者不再需要載入桌上型或平板電腦專用的 CSS),您應該使用下列其中一個外掛
mini-css-extract-plugin 提供掛勾,可依據您的需求進行擴充。
SyncWaterfallHook
在注入連結標籤的插入程式碼之前呼叫。應傳回字串
MiniCssExtractPlugin.getCompilationHooks(compilation).beforeTagInsert.tap(
"changeHref",
(source, varNames) =>
Template.asString([
source,
`${varNames.tag}.setAttribute("href", "/plugins/mini-css-extract-plugin/));`,
])
);
如果您尚未閱讀,請花點時間閱讀我們的貢獻指南。