跳至主要內容

撰寫自訂格式化器

格式化器是具有下列簽章的函式

/**
* @type {import('stylelint').Formatter}
*/
export default function formatter(results, returnValue) {
return "a string of formatted results";
}

其中第一個引數 (results) 是 Stylelint 結果物件 (類型 Array<StylelintResult>) 的陣列,形式為

// A Stylelint result object
{
"source": "path/to/file.css", // The filepath or PostCSS identifier like <input css 1>
"errored": true, // This is `true` if at least one rule with an "error"-level severity triggered a warning
"warnings": [
// Array of rule problem warning objects, each like the following ...
{
"line": 3,
"column": 12,
"endLine": 4,
"endColumn": 15,
"rule": "block-no-empty",
"severity": "error",
"text": "You should not have an empty block (block-no-empty)"
}
],
"deprecations": [
// Array of deprecation warning objects, each like the following ...
{
"text": "Feature X has been deprecated and will be removed in the next major version.",
"reference": "https://stylelint.dev.org.tw/docs/feature-x.md"
}
],
"invalidOptionWarnings": [
// Array of invalid option warning objects, each like the following ...
{
"text": "Invalid option X for rule Y"
}
],
"ignored": false // This is `true` if the file's path matches a provided ignore pattern
}

而第二個引數 (returnValue) 是具有下列一個或多個金鑰的物件 (類型 LinterResult)

{
"errored": false, // `true` if there were any warnings with "error" severity
"maxWarningsExceeded": {
// Present if Stylelint was configured with a `maxWarnings` count
"maxWarnings": 10,
"foundWarnings": 15
},
"ruleMetadata": {
"block-no-empty": {
"url": "https://stylelint.dev.org.tw/user-guide/rules/block-no-empty"
},
// other rules...
}
}

傳遞引數

您可以在格式化器中使用環境變數。例如,傳遞 SKIP_WARNINGS

SKIP_WARNINGS=true stylelint "*.css" --custom-formatter ./my-formatter.js

或者,您可以建立一個單獨的格式化程式,並將內建 JSON 格式化程式的輸出導向其中

stylelint -f json "*.css" 2>&1 | my-program-that-reads-JSON --option

stylelint.formatters

Stylelint 的內部格式化程式公開在 stylelint.formatters 中。