编写自定义格式化程序
¥Writing custom formatters
格式化程序是具有以下签名的函数:
¥A formatter is a function with the following signature:
/**
* @type {import('stylelint').Formatter}
*/
export default function formatter(results, returnValue) {
return "a string of formatted results";
}
其中第一个参数 (results
) 是 Stylelint 结果对象数组(类型 Array<StylelintResult>
),格式如下:
¥Where the first argument (results
) is an array of Stylelint result objects (type Array<StylelintResult>
) in the form:
// 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.nodejs.cn/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
),具有以下一个或多个键:
¥And the second argument (returnValue
) is an object (type LinterResult
) with one or more of the following keys:
{
"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.nodejs.cn/user-guide/rules/block-no-empty"
}
// other rules...
}
}
传递参数
¥Passing arguments
你可以在格式化程序中使用环境变量。例如,传递 SKIP_WARNINGS
:
¥You can use environmental variables in your formatter. For example, pass SKIP_WARNINGS
:
SKIP_WARNINGS=true stylelint "*.css" --custom-formatter ./my-formatter.js
或者,你可以创建一个单独的格式化程序,并将内置 JSON 格式化程序的输出通过管道传输到其中:
¥Alternatively, you can create a separate formatting program and pipe the output from the built-in JSON formatter into it:
stylelint -f json "*.css" 2>&1 | my-program-that-reads-JSON --option
stylelint.formatters
Stylelint 的内部格式化程序在 stylelint.formatters
中公开暴露。
¥Stylelint's internal formatters are exposed publicly in stylelint.formatters
.
共享格式化程序
¥Sharing formatters
在 package.json
中使用 stylelint-formatter
关键字。例如:
¥Use the stylelint-formatter
keyword within your package.json
. For example:
{
"keywords": ["stylelint", "stylelint-formatter"]
}