css-loader

免責聲明: css-loader 是由社群成員維護的第三方套件,它可能不具備與 webpack 相同的支援、安全政策或授權,且並非由 webpack 維護。

npm node tests coverage discussion size

css-loader 會將 @importurl() 解釋為 import/require(),並會解析它們。

入門

警告

若要使用最新版本的 css-loader,需要 webpack@5

首先,您需要安裝 css-loader

npm install --save-dev css-loader

yarn add -D css-loader

pnpm add -D css-loader

然後將外掛新增到您的 webpack 設定。例如

file.js

import css from "file.css";

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

並透過您偏好的方法執行 webpack

如果因為某種原因,您需要將 CSS 萃取為檔案(亦即不要將 CSS 儲存在 JS 模組中),您可能想要查看 建議範例

選項

url

類型

type url =
  | boolean
  | {
      filter: (url: string, resourcePath: string) => boolean;
    };

預設值:true

允許啟用/停用處理 CSS 函式 urlimage-set。如果設定為 falsecss-loader 將不會剖析在 urlimage-set 中指定的任何路徑。也可以傳遞函式來根據資產的路徑動態控制此行為。從版本 4.0.0 開始,絕對路徑會根據伺服器根目錄進行剖析。

範例解析

url(image.png) => require('./image.png')
url('image.png') => require('./image.png')
url(./image.png) => require('./image.png')
url('./image.png') => require('./image.png')
url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')

若要從 node_modules 路徑(包含 resolve.modules)和 alias 匯入資產,請在前面加上 ~

url(~module/image.png) => require('module/image.png')
url('~module/image.png') => require('module/image.png')
url(~aliasDirectory/image.png) => require('otherDirectory/image.png')

boolean

啟用/停用 url() 解析。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          url: true,
        },
      },
    ],
  },
};

object

允許篩選 url()。所有經過篩選的 url() 都將不會被解析(保留在程式碼中,就像它們被寫入的那樣)。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          url: {
            filter: (url, resourcePath) => {
              // resourcePath - path to css file

              // Don't handle `img.png` urls
              if (url.includes("img.png")) {
                return false;
              }

              // Don't handle images under root-relative /external_images/
              if (/^\/external_images\//.test(path)) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

import

類型

type importFn =
  | boolean
  | {
      filter: (
        url: string,
        media: string,
        resourcePath: string,
        supports?: string,
        layer?: string
      ) => boolean;
    };

預設值:true

允許啟用/停用 @import at-rules 處理。控制 @import 解析。@import 中的絕對 URL 會在執行時期代碼中移動。

範例解析

@import 'style.css' => require('./style.css')
@import url(style.css) => require('./style.css')
@import url('style.css') => require('./style.css')
@import './style.css' => require('./style.css')
@import url(./style.css) => require('./style.css')
@import url('./style.css') => require('./style.css')
@import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime

若要從 node_modules 路徑匯入樣式(包括 resolve.modules),以及 alias,請使用 ~ 為其加上前綴

@import url(~module/style.css) => require('module/style.css')
@import url('~module/style.css') => require('module/style.css')
@import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')

boolean

啟用/停用 @import 解析。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          import: true,
        },
      },
    ],
  },
};

object

filter

類型

type filter = (url: string, media: string, resourcePath: string) => boolean;

預設:undefined

允許篩選 @import。所有經過篩選的 @import 都將不會解析(保留在代碼中,就像它們被寫入的那樣)。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          import: {
            filter: (url, media, resourcePath) => {
              // resourcePath - path to css file

              // Don't handle `style.css` import
              if (url.includes("style.css")) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

modules

類型

type modules =
  | boolean
  | "local"
  | "global"
  | "pure"
  | "icss"
  | {
      auto: boolean | regExp | ((resourcePath: string) => boolean);
      mode:
        | "local"
        | "global"
        | "pure"
        | "icss"
        | ((resourcePath) => "local" | "global" | "pure" | "icss");
      localIdentName: string;
      localIdentContext: string;
      localIdentHashSalt: string;
      localIdentHashFunction: string;
      localIdentHashDigest: string;
      localIdentRegExp: string | regExp;
      getLocalIdent: (
        context: LoaderContext,
        localIdentName: string,
        localName: string
      ) => string;
      namedExport: boolean;
      exportGlobals: boolean;
      exportLocalsConvention:
        | "asIs"
        | "camelCase"
        | "camelCaseOnly"
        | "dashes"
        | "dashesOnly"
        | ((name: string) => string);
      exportOnlyLocals: boolean;
    };

預設:undefined

允許啟用/停用 CSS 模組或 ICSS 並設定組態

  • undefined - 為符合 /\.module\.\w+$/i.test(filename)/\.icss\.\w+$/i.test(filename) 正規表示法的檔案啟用 CSS 模組。
  • true - 為所有檔案啟用 CSS 模組。
  • false - 為所有檔案停用 CSS 模組。
  • string - 為所有檔案停用 CSS 模組並設定 mode 選項,更多資訊請參閱 此處
  • object - 為所有檔案啟用 CSS 模組,如果未指定 modules.auto 選項,否則 modules.auto 選項將決定是否為 CSS 模組,更多資訊請參閱 此處

modules 選項啟用/停用 CSS 模組 規格並設定基本行為。

使用 false 值會提升效能,因為我們避免剖析 CSS 模組 功能,這對於使用純粹 CSS 或使用其他技術的開發人員來說很有用。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: true,
        },
      },
    ],
  },
};

功能

範圍

使用 local 值需要您指定 :global 類別。使用 global 值需要您指定 :local 類別。使用 pure 值需要選取器至少包含一個本地類別或 ID。

您可以在 這裡 找到更多資訊。

樣式可以設定為本地範圍,以避免設定為全域範圍。

語法 :local(.className) 可用於在本地範圍宣告 className。本地識別碼由模組匯出。

使用 :local(沒有括弧)可以為這個選取器開啟本地模式。:global(.className) 符號可宣告明確的全域選取器。使用 :global(沒有括弧)可以為這個選取器開啟全域模式。

載入器會以唯一識別碼取代本地選取器。所選取的唯一識別碼由模組匯出。

:local(.className) {
  background: red;
}
:local .className {
  color: green;
}
:local(.className .subClass) {
  color: green;
}
:local .className .subClass :global(.global-class-name) {
  color: blue;
}
._23_aKvs-b8bW2Vg3fwHozO {
  background: red;
}
._23_aKvs-b8bW2Vg3fwHozO {
  color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
  color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
  color: blue;
}

注意

識別碼已匯出

exports.locals = {
  className: "_23_aKvs-b8bW2Vg3fwHozO",
  subClass: "_13LGdX8RMStbBE9w-t0gZ1",
};

建議本地選取器使用駝峰式大小寫。在匯入的 JS 模組中較容易使用。

您可以使用 :local(#someId),但不建議這樣做。請使用類別,不要使用 ID。

組成

在宣告本地類別名稱時,您可以從另一個本地類別名稱組成一個本地類別。

:local(.className) {
  background: red;
  color: yellow;
}

:local(.subClass) {
  composes: className;
  background: blue;
}

這不會對 CSS 本身造成任何變更,但會匯出多個類別名稱。

exports.locals = {
  className: "_23_aKvs-b8bW2Vg3fwHozO",
  subClass: "_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO",
};
._23_aKvs-b8bW2Vg3fwHozO {
  background: red;
  color: yellow;
}

._13LGdX8RMStbBE9w-t0gZ1 {
  background: blue;
}
匯入

從其他模組匯入本機類別名稱。

注意

我們強烈建議您在匯入檔案時指定副檔名,因為可以匯入任何副檔名的檔案,而且無法預先知道要使用哪個檔案。

:local(.continueButton) {
  composes: button from "library/button.css";
  background: red;
}
:local(.nameEdit) {
  composes: edit highlight from "./edit.css";
  background: red;
}

若要從多個模組匯入,請使用多個 composes: 規則。

:local(.className) {
  composes: edit highlight from "./edit.css";
  composes: button from "module/button.css";
  composes: classFromThisModule;
  background: red;
}

您可以使用 @value 指定要在整個文件中重複使用的值。

我們建議值使用前綴 v-、選取器使用 s-、媒體 at 規則使用 m-

@value v-primary: #BF4040;
@value s-black: black-selector;
@value m-large: (min-width: 960px);

.header {
  color: v-primary;
  padding: 0 10px;
}

.s-black {
  color: black;
}

@media m-large {
  .header {
    padding: 0 20px;
  }
}

布林值

啟用 CSS 模組 功能。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: true,
        },
      },
    ],
  },
};

字串

啟用 CSS 模組 功能並設定 模式

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          // Using `local` value has same effect like using `modules: true`
          modules: "global",
        },
      },
    ],
  },
};

物件

啟用 CSS 模組 功能並設定其選項。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            mode: "local",
            auto: true,
            exportGlobals: true,
            localIdentName: "[path][name]__[local]--[hash:base64:5]",
            localIdentContext: path.resolve(__dirname, "src"),
            localIdentHashSalt: "my-custom-hash",
            namedExport: true,
            exportLocalsConvention: "camelCase",
            exportOnlyLocals: false,
          },
        },
      },
    ],
  },
};
自動

類型

type auto =
  | boolean
  | regExp
  | ((
      resourcePath: string,
      resourceQuery: string,
      resourceFragment: string
    ) => boolean);

預設:undefined

模組 選項為物件時,允許根據檔名、查詢或片段自動啟用 CSS 模組/ICSS。

可能的值

  • 未定義 - 為所有檔案啟用 CSS 模組。
  • true - 為符合 /\.module\.\w+$/i.test(filename)/\.icss\.\w+$/i.test(filename) 正規表示式的所有檔案啟用 CSS 模組。
  • false - 停用 CSS 模組。
  • RegExp - 為符合 /RegExp/i.test(filename) 正規表示式的所有檔案啟用 CSS 模組。
  • 函式 - 根據滿足您的篩選函式檢查的檔名,為檔案啟用 CSS 模組。
布林值

可能的值

  • true - 啟用 CSS 模組或可互通的 CSS 格式,將 modules.mode 選項設定為符合 /\.module(s)?\.\w+$/i.test(filename) 條件的所有檔案的 local 值,或將 modules.mode 選項設定為符合 /\.icss\.\w+$/i.test(filename) 條件的所有檔案的 icss
  • false - 根據檔名停用 CSS 模組或可互通的 CSS 格式

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            auto: true,
          },
        },
      },
    ],
  },
};
RegExp

根據符合正規表示式檢查的檔名,為檔案啟用 CSS 模組。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            auto: /\.custom-module\.\w+$/i,
          },
        },
      },
    ],
  },
};
function

根據符合篩選器函數檢查的檔名、查詢或片段,為檔案啟用 CSS 模組。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            auto: (resourcePath, resourceQuery, resourceFragment) => {
              return resourcePath.endsWith(".custom-module.css");
            },
          },
        },
      },
    ],
  },
};
mode

類型

type mode =
  | "local"
  | "global"
  | "pure"
  | "icss"
  | ((
      resourcePath: string,
      resourceQuery: string,
      resourceFragment: string
    ) => "local" | "global" | "pure" | "icss");

預設值:'local'

設定 mode 選項。當您要使用 local 模式時,可以省略值。

控制套用於輸入樣式的編譯層級。

localglobalpure 處理 classid 範圍以及 @value 值。icss 只會編譯低階 可互通 CSS 格式,用於宣告 CSS 與其他語言之間的 :import:export 相依性。

ICSS 為 CSS 模組支援提供基礎,並提供低階語法供其他工具實作自己的 CSS 模組變異。

string

可能的值 - localglobalpureicss

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            mode: "global",
          },
        },
      },
    ],
  },
};
function

允許根據檔名、查詢或片段設定 mode 選項的不同值。

可能的傳回值 - localglobalpureicss

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            // Callback must return "local", "global", or "pure" values
            mode: (resourcePath, resourceQuery, resourceFragment) => {
              if (/pure.css$/i.test(resourcePath)) {
                return "pure";
              }

              if (/global.css$/i.test(resourcePath)) {
                return "global";
              }

              return "local";
            },
          },
        },
      },
    ],
  },
};
localIdentName

類型

type localIdentName = string;

預設:'[hash:base64]'

允許設定產生的 local ident 名稱。

更多選項資訊請參閱

支援的樣板字串

  • [name] 資源的基本名稱
  • [folder] 資源相對於 compiler.context 選項或 modules.localIdentContext 選項的資料夾。
  • [path] 資源相對於 compiler.context 選項或 modules.localIdentContext 選項的路徑。
  • [file] - 檔名和路徑。
  • [ext] - 副檔名,包含開頭的 .
  • [hash] - 字串的雜湊,根據 localIdentHashSaltlocalIdentHashFunctionlocalIdentHashDigestlocalIdentHashDigestLengthlocalIdentContextresourcePathexportName 產生
  • [<hashFunction>:hash:<hashDigest>:<hashDigestLength>] - 雜湊和雜湊設定。
  • [local] - 原始類別。

建議

  • 開發時使用 '[path][name]__[local]'
  • 正式環境使用 '[hash:base64]'

[local] 佔位符包含原始類別。

注意:所有保留 (<>:"/\|?*) 和控制檔案系統字元 (不包含 [local] 佔位符中的字元) 都會轉換為 -

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentName: "[path][name]__[local]--[hash:base64:5]",
          },
        },
      },
    ],
  },
};
localIdentContext

類型

type localIdentContex = string;

預設:compiler.context

允許重新定義本地識別名稱的基本載入器內容。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentContext: path.resolve(__dirname, "src"),
          },
        },
      },
    ],
  },
};
localIdentHashSalt

類型

type localIdentHashSalt = string;

預設:undefined

允許新增自訂雜湊以產生更獨特的類別。如需更多資訊,請參閱 output.hashSalt

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentHashSalt: "hash",
          },
        },
      },
    ],
  },
};
localIdentHashFunction

類型

type localIdentHashFunction = string;

預設值:md4

允許指定雜湊函數以產生類別。如需更多資訊,請參閱 output.hashFunction

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentHashFunction: "md4",
          },
        },
      },
    ],
  },
};
localIdentHashDigest

類型

type localIdentHashDigest = string;

預設值:hex

允許指定雜湊摘要以產生類別。如需更多資訊,請參閱 output.hashDigest

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentHashDigest: "base64",
          },
        },
      },
    ],
  },
};
localIdentHashDigestLength

類型

type localIdentHashDigestLength = number;

預設值:20

允許指定雜湊摘要長度以產生類別。如需更多資訊,請參閱 output.hashDigestLength

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentHashDigestLength: 5,
          },
        },
      },
    ],
  },
};
hashStrategy

類型:'resource-path-and-local-name' | 'minimal-subset' 預設值:'resource-path-and-local-name'

計算雜湊時是否應使用本地名稱。

  • 'resource-path-and-local-name' 雜湊時同時使用資源路徑和本地名稱。模組中的每個識別碼都會取得自己的雜湊摘要,永遠如此。
  • 'minimal-subset' 自動偵測識別碼名稱是否可從雜湊中省略。使用此值可最佳化輸出以獲得更好的 GZIP 或 Brotli 壓縮。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            hashStrategy: "minimal-subset",
          },
        },
      },
    ],
  },
};
localIdentRegExp

類型

type localIdentRegExp = string | RegExp;

預設:undefined

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentRegExp: /page-(.*)\.css/i,
          },
        },
      },
    ],
  },
};
getLocalIdent

類型

type getLocalIdent = (
  context: LoaderContext,
  localIdentName: string,
  localName: string
) => string;

預設:undefined

允許指定函數以產生類別名稱。預設情況下,我們使用內建函數來產生類別名稱。如果自訂函數傳回 nullundefined,我們會改用內建函數來產生類別名稱。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            getLocalIdent: (context, localIdentName, localName, options) => {
              return "whatever_random_class_name";
            },
          },
        },
      },
    ],
  },
};
namedExport

類型

type namedExport = boolean;

預設值:false

啟用/停用 ES 模組對區域變數的命名匯出。

警告

區域變數的名稱會轉換為駝峰式大小寫,也就是說 exportLocalsConvention 選項預設值為 camelCaseOnly。你可以將它設定回任何其他有效的選項,但不是有效 JavaScript 識別字元的選擇器可能會遇到問題,因為它們沒有實作完整的模組規格。

警告

除非 exportLocalsConvention"asIs",否則不允許在 CSS 類別名稱中使用 JavaScript 保留字。

styles.css

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

index.js

import * as styles from "./styles.css";

console.log(styles.fooBaz, styles.bar);
// or if using `exportLocalsConvention: "asIs"`:
console.log(styles["foo-baz"], styles.bar);

你可以使用以下方式啟用 ES 模組的命名匯出

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          esModule: true,
          modules: {
            namedExport: true,
          },
        },
      },
    ],
  },
};

若要設定 namedExport 的自訂名稱,可以使用 exportLocalsConvention 選項作為函式。範例如下,在 範例 區段中。

exportGlobals

類型

type exportsGLobals = boolean;

預設值:false

允許 css-loader 從全域類別或 ID 匯出名稱,這樣你就可以將它用作區域變數名稱。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            exportGlobals: true,
          },
        },
      },
    ],
  },
};
exportLocalsConvention

類型

type exportLocalsConvention =
  | "asIs"
  | "camelCase"
  | "camelCaseOnly"
  | "dashes"
  | "dashesOnly"
  | ((name: string) => string);

預設值:根據 modules.namedExport 選項值,如果為 true - camelCaseOnly,否則為 asIs

匯出類別名稱的樣式。

字串

預設情況下,匯出的 JSON 鍵會反映類別名稱(也就是說 asIs 值)。

名稱類型說明
'asIs'字串類別名稱會原樣匯出。
'camelCase'字串類別名稱會轉為駝峰式大小寫,但原始類別名稱不會從區域變數中移除
'camelCaseOnly'字串類別名稱會轉為駝峰式大小寫,原始類別名稱會從區域變數中移除
'破折號'字串僅會將類別名稱中的破折號轉換成駝峰式大小寫
'dashesOnly'字串會將類別名稱中的破折號轉換成駝峰式大小寫,並從 locals 中移除原始類別名稱

file.css

.class-name {
}

file.js

import { className } from "file.css";

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            exportLocalsConvention: "camelCase",
          },
        },
      },
    ],
  },
};
函式

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            exportLocalsConvention: function (name) {
              return name.replace(/-/g, "_");
            },
          },
        },
      },
    ],
  },
};

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            exportLocalsConvention: function (name) {
              return [
                name.replace(/-/g, "_"),
                // dashesCamelCase
                name.replace(/-+(\w)/g, (match, firstLetter) =>
                  firstLetter.toUpperCase()
                ),
              ];
            },
          },
        },
      },
    ],
  },
};
exportOnlyLocals

類型

type exportOnlyLocals = boolean;

預設值:false

僅匯出 locals。

當您使用CSS 模組進行預先渲染(例如 SSR)時很有用。對於使用 mini-css-extract-plugin 進行預先渲染,您應該在預先渲染套件中使用此選項,而不是 style-loader!css-loader。它不會嵌入 CSS,只會匯出識別碼對應。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            exportOnlyLocals: true,
          },
        },
      },
    ],
  },
};

importLoaders

類型

type importLoaders = number;

預設:0

允許啟用/停用或設定在 @import at 規則、CSS 模組和 ICSS 匯入(例如 @import/composes/@value value from './values.css'/等)之前套用的載入器數量。

importLoaders 選項允許您設定在 css-loader 之前應套用於 @imported 資源和 CSS 模組/ICSS 匯入的載入器數量。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 2,
              // 0 => no loaders (default);
              // 1 => postcss-loader;
              // 2 => postcss-loader, sass-loader
            },
          },
          "postcss-loader",
          "sass-loader",
        ],
      },
    ],
  },
};

當模組系統(例如 webpack)支援依來源進行載入器配對時,這可能會在未來有所改變。

sourceMap

類型

type sourceMap = boolean;

預設:取決於 compiler.devtool

預設產生原始碼對應表會依賴 devtool 選項。除了 evalfalse 值之外,所有值都會啟用原始碼對應表產生。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          sourceMap: true,
        },
      },
    ],
  },
};

esModule

類型

type esModule = boolean;

預設值:true

預設,css-loader 會產生使用 ES 模組語法的 JS 模組。在某些情況下,使用 ES 模組是有利的,例如 模組串接樹狀搖晃 的情況。

你可以使用以下方式啟用 CommonJS 模組語法

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          esModule: false,
        },
      },
    ],
  },
};

exportType

類型

type exportType = "array" | "string" | "css-style-sheet";

預設:'array'

允許將樣式作為陣列匯出,其中包含模組、字串或 可建構樣式表(例如 CSSStyleSheet)。預設值為 'array',也就是說,載入器會匯出具備特定 API 的模組陣列,這個 API 會用於 style-loader 或其他載入器。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        assert: { type: "css" },
        loader: "css-loader",
        options: {
          exportType: "css-style-sheet",
        },
      },
    ],
  },
};

src/index.js

import sheet from "./styles.css" assert { type: "css" };

document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];

'array'

預設匯出是具備特定 API 的模組陣列,這個 API 會用於 style-loader 或其他載入器。

webpack.config.js

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

src/index.js

// `style-loader` applies styles to DOM
import "./styles.css";

'string'

警告

你不能將 style-loadermini-css-extract-plugin 與這個值一起使用。

警告

如果你想將 esModule 選項與 CSS 模組 一起使用,則應該啟用這個選項,預設會對區域變數使用 命名匯出

預設匯出是 string

webpack.config.js

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

src/index.js

import sheet from "./styles.css";

console.log(sheet);

'css-style-sheet'

警告

@import 規則尚未允許,更多 資訊

警告

您不再需要 style-loader,請移除它。

警告

如果你想將 esModule 選項與 CSS 模組 一起使用,則應該啟用這個選項,預設會對區域變數使用 命名匯出

警告

由於 錯誤,目前 Chrome 不支援原始碼對應。

預設匯出為 可建構樣式表(即 CSSStyleSheet)。

適用於 自訂元素 和陰影 DOM。

更多資訊

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        assert: { type: "css" },
        loader: "css-loader",
        options: {
          exportType: "css-style-sheet",
        },
      },

      // For Sass/SCSS:
      //
      // {
      //   assert: { type: "css" },
      //   rules: [
      //     {
      //       loader: "css-loader",
      //       options: {
      //         exportType: "css-style-sheet",
      //         // Other options
      //       },
      //     },
      //     {
      //       loader: "sass-loader",
      //       options: {
      //         // Other options
      //       },
      //     },
      //   ],
      // },
    ],
  },
};

src/index.js

// Example for Sass/SCSS:
// import sheet from "./styles.scss" assert { type: "css" };

// Example for CSS modules:
// import sheet, { myClass } from "./styles.scss" assert { type: "css" };

// Example for CSS:
import sheet from "./styles.css" assert { type: "css" };

document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];

基於遷移目的,您可以使用下列組態

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        oneOf: [
          {
            assert: { type: "css" },
            loader: "css-loader",
            options: {
              exportType: "css-style-sheet",
              // Other options
            },
          },
          {
            use: [
              "style-loader",
              {
                loader: "css-loader",
                options: {
                  // Other options
                },
              },
            ],
          },
        ],
      },
    ],
  },
};

範例

建議

對於 production 建構,建議從您的套件中萃取 CSS,以便稍後並行載入 CSS/JS 資源。這可以使用 mini-css-extract-plugin 來達成,因為它會建立獨立的 css 檔案。對於 development 模式(包括 webpack-dev-server),您可以使用 style-loader,因為它會使用多個 <style></style> 將 CSS 注入 DOM,而且執行速度較快。

注意

請勿同時使用 style-loadermini-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$/i,
        use: [
          devMode ? "style-loader" : MiniCssExtractPlugin.loader,
          "css-loader",
          "postcss-loader",
          "sass-loader",
        ],
      },
    ],
  },
  plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
};

使用 /* webpackIgnore: true */ 註解停用 URL 解析

透過 /* webpackIgnore: true */ 註解,可以停用規則和個別宣告的來源處理。

/* webpackIgnore: true */
@import url(./basic.css);
@import /* webpackIgnore: true */ url(./imported.css);

.class {
  /* Disabled url handling for the all urls in the 'background' declaration */
  color: red;
  /* webpackIgnore: true */
  background: url("./url/img.png"), url("./url/img.png");
}

.class {
  /* Disabled url handling for the first url in the 'background' declaration */
  color: red;
  background:
    /* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png");
}

.class {
  /* Disabled url handling for the second url in the 'background' declaration */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */ url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* Disabled url handling for the second url in the 'background' declaration */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */
    url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* Disabled url handling for third and sixth urls in the 'background-image' declaration */
  background-image: image-set(
    url(./url/img.png) 2x,
    url(./url/img.png) 3x,
    /* webpackIgnore:  true */ url(./url/img.png) 4x,
    url(./url/img.png) 5x,
    url(./url/img.png) 6x,
    /* webpackIgnore:  true */
    url(./url/img.png) 7x
  );
}

資產

下列 webpack.config.js 可以載入 CSS 檔案、將小型 PNG/JPG/GIF/SVG 影像和字型嵌入為 資料 URL,以及將較大的檔案複製到輸出目錄。

適用於 webpack v5

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        // More information here https://webpack.dev.org.tw/guides/asset-modules/
        type: "asset",
      },
    ],
  },
};

萃取

建議在生產建置中從您的套件萃取 CSS,以便稍後能平行載入 CSS/JS 資源。

  • 這可以使用 mini-css-extract-plugin 在生產模式下執行時萃取 CSS 來達成。

  • 或者,如果要追求更好的開發效能和模擬生產的 CSS 輸出。extract-css-chunks-webpack-plugin 提供了 mini-css-extract-plugin 的熱模組重新載入友善、延伸版本。在開發中 HMR 真實的 CSS 檔案,在非開發中則像 mini-css 一樣運作

純 CSS、CSS 模組和 PostCSS

當您的專案中有純 CSS(沒有 CSS 模組)、CSS 模組和 PostCSS 時,您可以使用這個設定

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        // For pure CSS - /\.css$/i,
        // For Sass/SCSS - /\.((c|sa|sc)ss)$/i,
        // For Less - /\.((c|le)ss)$/i,
        test: /\.((c|sa|sc)ss)$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              // Run `postcss-loader` on each CSS `@import` and CSS modules/ICSS imports, do not forget that `sass-loader` compile non CSS `@import`'s into a single file
              // If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2`
              importLoaders: 1,
            },
          },
          {
            loader: "postcss-loader",
            options: { plugins: () => [postcssPresetEnv({ stage: 0 })] },
          },
          // Can be `less-loader`
          {
            loader: "sass-loader",
          },
        ],
      },
      // For webpack v5
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        // More information here https://webpack.dev.org.tw/guides/asset-modules/
        type: "asset",
      },
    ],
  },
};

使用別名解析未解析的 URL

index.css

.class {
  background: url(/assets/unresolved/img.png);
}

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  resolve: {
    alias: {
      "/assets/unresolved/img.png": path.resolve(
        __dirname,
        "assets/real-path-to-img/img.png"
      ),
    },
  },
};

使用自訂匯出名稱的命名匯出

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            namedExport: true,
            exportLocalsConvention: function (name) {
              return name.replace(/-/g, "_");
            },
          },
        },
      },
    ],
  },
};

分離僅限可互通 CSSCSS 模組功能

以下設定範例僅允許可互通 CSS功能(例如:import:export),而不使用進一步的CSS 模組功能,方法是為所有不符合*.module.scss命名慣例的檔案設定mode選項。這是作為參考,因為在 v4 之前,將ICSS功能套用至所有檔案是css-loader的預設行為。同時,在此範例中所有符合*.module.scss的檔案都視為CSS 模組

假設有一個範例案例,專案需要將畫布繪製變數與 CSS 同步,畫布繪製使用與 HTML 背景相同的顏色(在 JavaScript 中以顏色名稱設定,在 CSS 中以類別名稱設定)。

webpack.config.js

module.exports = {
  module: {
    rules: [
      // ...
      // --------
      // SCSS ALL EXCEPT MODULES
      {
        test: /\.scss$/i,
        exclude: /\.module\.scss$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
            options: {
              importLoaders: 1,
              modules: {
                mode: "icss",
              },
            },
          },
          {
            loader: "sass-loader",
          },
        ],
      },
      // --------
      // SCSS MODULES
      {
        test: /\.module\.scss$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
            options: {
              importLoaders: 1,
              modules: {
                mode: "local",
              },
            },
          },
          {
            loader: "sass-loader",
          },
        ],
      },
      // --------
      // ...
    ],
  },
};

variables.scss

檔案僅視為 ICSS

$colorBackground: red;
:export {
  colorBackgroundCanvas: $colorBackground;
}

Component.module.scss

檔案視為 CSS 模組

@import "variables.scss";
.componentClass {
  background-color: $colorBackground;
}

Component.jsx

同時在 JavaScript 中使用 CSS 模組 功能和 SCSS 變數。

import svars from "variables.scss";
import styles from "Component.module.scss";

// Render DOM with CSS modules class name
// <div className={styles.componentClass}>
//   <canvas ref={mountsCanvas}/>
// </div>

// Somewhere in JavaScript canvas drawing code use the variable directly
// const ctx = mountsCanvas.current.getContext('2d',{alpha: false});
ctx.fillStyle = `${svars.colorBackgroundCanvas}`;

貢獻

如果您尚未閱讀,請花點時間閱讀我們的貢獻指南。

CONTRIBUTING

授權

MIT