UNPKG

8.36 kBMarkdownView Raw
1# Writing plugins
2
3Plugins are rules and sets of rules built by the community.
4
5We recommend your plugin adheres to [stylelint's conventions](rules.md) for:
6
7- names
8- options
9- messages
10- tests
11- docs
12
13## The anatomy of a plugin
14
15```js
16// Abbreviated example
17const stylelint = require("stylelint");
18
19const ruleName = "plugin/foo-bar";
20const messages = stylelint.utils.ruleMessages(ruleName, {
21 expected: "Expected ..."
22});
23
24module.exports = stylelint.createPlugin(ruleName, function (
25 primaryOption,
26 secondaryOptionObject
27) {
28 return function (postcssRoot, postcssResult) {
29 const validOptions = stylelint.utils.validateOptions(
30 postcssResult,
31 ruleName,
32 {
33 /* .. */
34 }
35 );
36
37 if (!validOptions) {
38 return;
39 }
40
41 // ... some logic ...
42 stylelint.utils.report({
43 /* .. */
44 });
45 };
46});
47
48module.exports.ruleName = ruleName;
49module.exports.messages = messages;
50```
51
52Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`, to ensure it never clashes with the built-in rules. If your plugin provides only a single rule or you can't think of a good namespace, you can use `plugin/my-rule`. _You should document your plugin's rule name (and namespace) because users need to use them in their config._
53
54Use `stylelint.createPlugin(ruleName, ruleFunction)` to ensure that your plugin is set up properly alongside other rules.
55
56For your plugin rule to work with the [standard configuration format](../user-guide/configure.md#rules), `ruleFunction` should accept 2 arguments:
57
58- the primary option
59- optionally, a secondary options object
60
61If your plugin rule supports [autofixing](rules.md#add-autofix), then `ruleFunction` should also accept a third argument: `context`. You should try to support the `disableFix` option in your secondary options object. Within the rule, don't perform autofixing if the user has passed a `disableFix` option for your rule.
62
63`ruleFunction` should return a function that is essentially a little [PostCSS plugin](https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md). It takes 2 arguments:
64
65- the PostCSS Root (the parsed AST)
66- the PostCSS LazyResult
67
68You'll have to [learn about the PostCSS API](https://api.postcss.org/).
69
70### Asynchronous rules
71
72You can return a `Promise` instance from your plugin function to create an asynchronous rule.
73
74```js
75// Abbreviated asynchronous example
76const stylelint = require("stylelint");
77
78const ruleName = "plugin/foo-bar-async";
79const messages = stylelint.utils.ruleMessages(ruleName, {
80 expected: "Expected ..."
81});
82
83module.exports = stylelint.createPlugin(ruleName, function (
84 primaryOption,
85 secondaryOptionObject
86) {
87 return function (postcssRoot, postcssResult) {
88 const validOptions = stylelint.utils.validateOptions(
89 postcssResult,
90 ruleName,
91 {
92 /* .. */
93 }
94 );
95
96 if (!validOptions) {
97 return;
98 }
99
100 return new Promise(function (resolve) {
101 // some async operation
102 setTimeout(function () {
103 // ... some logic ...
104 stylelint.utils.report({
105 /* .. */
106 });
107 resolve();
108 }, 1);
109 });
110 };
111});
112
113module.exports.ruleName = ruleName;
114module.exports.messages = messages;
115```
116
117## `stylelint.utils`
118
119stylelint exposes some useful utilities.
120
121### `stylelint.utils.report`
122
123Adds violations from your plugin to the list of violations that stylelint will report to the user.
124
125Use `stylelint.utils.report` to ensure your plugin respects disabled ranges and other possible future features of stylelint. _Do not use PostCSS's `node.warn()` method directly._
126
127### `stylelint.utils.ruleMessages`
128
129Tailors your messages to the format of standard stylelint rules.
130
131### `stylelint.utils.validateOptions`
132
133Validates the options for your rule.
134
135### `stylelint.utils.checkAgainstRule`
136
137Checks CSS against a standard stylelint rule _within your own rule_. This function provides power and flexibility for plugins authors who wish to modify, constrain, or extend the functionality of existing stylelint rules.
138
139It accepts an options object and a callback that is invoked with warnings from the specified rule. The options are:
140
141- `ruleName`: the name of the rule you are invoking
142- `ruleSettings`: settings for the rule you are invoking
143- `root`: the root node to run this rule against
144
145Use the warning to create a _new_ warning _from your plugin rule_ that you report with `stylelint.utils.report`.
146
147For example, imagine you want to create a plugin that runs `at-rule-no-unknown` with a built-in list of exceptions for at-rules provided by your preprocessor-of-choice:
148
149```js
150const allowableAtRules = [
151 /* .. */
152];
153
154function myPluginRule(primaryOption, secondaryOptionObject) {
155 return function (postcssRoot, postcssResult) {
156 const defaultedOptions = Object.assign({}, secondaryOptionObject, {
157 ignoreAtRules: allowableAtRules.concat(options.ignoreAtRules || [])
158 });
159
160 stylelint.utils.checkAgainstRule(
161 {
162 ruleName: "at-rule-no-unknown",
163 ruleSettings: [primaryOption, defaultedOptions],
164 root: postcssRoot
165 },
166 (warning) => {
167 stylelint.utils.report({
168 message: myMessage,
169 ruleName: myRuleName,
170 result: postcssResult,
171 node: warning.node,
172 line: warning.line,
173 column: warning.column
174 });
175 }
176 );
177 };
178}
179```
180
181## `stylelint.rules`
182
183All of the rule functions are available at `stylelint.rules`. This allows you to build on top of existing rules for your particular needs.
184
185A typical use-case is to build in more complex conditionals that the rule's options allow for. For example, maybe your codebase uses special comment directives to customize rule options for specific stylesheets. You could build a plugin that checks those directives and then runs the appropriate rules with the right options (or doesn't run them at all).
186
187All rules share a common signature. They are a function that accepts two arguments: a primary option and a secondary options object. And that functions returns a function that has the signature of a PostCSS plugin, expecting a PostCSS root and result as its arguments.
188
189Here's an example of a plugin that runs `color-hex-case` only if there is a special directive `@@check-color-hex-case` somewhere in the stylesheet:
190
191```js
192module.exports = stylelint.createPlugin(ruleName, function (expectation) {
193 const runColorHexCase = stylelint.rules["color-hex-case"](expectation);
194
195 return (root, result) => {
196 if (root.toString().indexOf("@@check-color-hex-case") === -1) {
197 return;
198 }
199
200 runColorHexCase(root, result);
201 };
202});
203```
204
205## Allow primary option arrays
206
207If your plugin can accept an array as its primary option, you must designate this by setting the property `primaryOptionArray = true` on your rule function. For more information, check out the ["Working on rules"](rules.md) doc.
208
209## External helper modules
210
211In addition to the standard parsers mentioned in the ["Working on rules"](rules.md) doc, there are other external modules used within stylelint that we recommend using. These include:
212
213- [normalize-selector](https://github.com/getify/normalize-selector): normalize CSS selectors.
214- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector): given a (nested) selector in a PostCSS AST, return an array of resolved selectors.
215
216Have a look through [stylelint's internal utils](https://github.com/stylelint/stylelint/tree/master/lib/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into an external module.
217
218## Peer dependencies
219
220You should express, within the `peerDependencies` key (and **not** within the `dependencies` key) of your plugin's `package.json`, what version(s) of stylelint your plugin can be used with. This is to ensure that different versions of stylelint are not unexpectedly installed.
221
222For example, to express that your plugin can be used with stylelint versions 7 and 8:
223
224```json
225{
226 "peerDependencies": {
227 "stylelint": "^7.0.0 || ^8.0.0"
228 }
229}
230```
231
232## Plugin packs
233
234To make a single module provide multiple rules, export an array of plugin objects (rather than a single object).
235
236## Sharing plugins and plugin packs
237
238Use the `stylelint-plugin` keyword within your `package.json`.