1 | # Working on rules
|
2 |
|
3 | Please help us create, enhance, and debug our rules!
|
4 |
|
5 | ## Add a rule
|
6 |
|
7 | You should:
|
8 |
|
9 | 1. Get yourself ready to [contribute code](../../CONTRIBUTING.md#code-contributions).
|
10 | 2. Familiarize yourself with the [conventions and patterns](../user-guide/rules/about.md) for rules.
|
11 |
|
12 | ### Write the rule
|
13 |
|
14 | When writing the rule, you should:
|
15 |
|
16 | - make the rule strict by default
|
17 | - add secondary `ignore` options to make the rule more permissive
|
18 | - not include code specific to language extensions, e.g. SCSS
|
19 |
|
20 | You should make use of the:
|
21 |
|
22 | - PostCSS API
|
23 | - construct-specific parsers
|
24 | - utility functions
|
25 |
|
26 | #### PostCSS API
|
27 |
|
28 | Use the [PostCSS API](https://api.postcss.org/) to navigate and analyze the CSS syntax tree. We recommend using the `walk` iterators (e.g. `walkDecls`), rather than using `forEach` to loop through the nodes.
|
29 |
|
30 | When using array methods on nodes, e.g. `find`, `some`, `filter` etc, you should explicitly check the `type` property of the node before attempting to access other properties. For example:
|
31 |
|
32 | ```js
|
33 | const hasProperty = nodes.find(
|
34 | ({ type, prop }) => type === "decl" && prop === propertyName
|
35 | );
|
36 | ```
|
37 |
|
38 | Use `node.raws` instead of `node.raw()` when accessing raw strings from the [PostCSS AST](https://astexplorer.net/#/gist/ef718daf3e03f1d200b03dc5a550ec60/c8cbe9c6809a85894cebf3fb66de46215c377f1a).
|
39 |
|
40 | #### Construct-specific parsers
|
41 |
|
42 | Depending on the rule, we also recommend using:
|
43 |
|
44 | - [postcss-value-parser](https://github.com/TrySound/postcss-value-parser)
|
45 | - [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser)
|
46 |
|
47 | There are significant benefits to using these parsers instead of regular expressions or `indexOf` searches (even if they aren't always the most performant method).
|
48 |
|
49 | #### Utility functions
|
50 |
|
51 | stylelint has [utility functions](https://github.com/stylelint/stylelint/tree/master/lib/utils) that are used in existing rules and might prove useful to you, as well. Please look through those so that you know what's available. (And if you have a new function that you think might prove generally helpful, let's add it to the list!).
|
52 |
|
53 | Use the:
|
54 |
|
55 | - `validateOptions()` utility to warn users about invalid options
|
56 | - `isStandardSyntax*` utilities to ignore non-standard syntax
|
57 |
|
58 | ### Add options
|
59 |
|
60 | Only add an option to a rule if it addresses a _requested_ use case to avoid polluting the tool with unused features.
|
61 |
|
62 | If your rule can accept an array as its primary option, you must designate this by setting the property `primaryOptionArray = true` on your rule function. For example:
|
63 |
|
64 | ```js
|
65 | function rule(primary, secondary) {
|
66 | return (root, result) => {
|
67 | /* .. */
|
68 | };
|
69 | }
|
70 |
|
71 | rule.primaryOptionArray = true;
|
72 |
|
73 | module.exports = rule;
|
74 | ```
|
75 |
|
76 | There is one caveat here: If your rule accepts a primary option array, it cannot also accept a primary option object. Whenever possible, if you want your rule to accept a primary option array, you should make an array the only possibility, instead of allowing for various data structures.
|
77 |
|
78 | ### Add autofix
|
79 |
|
80 | Depending on the rule, it might be possible to automatically fix the rule's violations by mutating the PostCSS AST (Abstract Syntax Tree) using the [PostCSS API](http://api.postcss.org/).
|
81 |
|
82 | Add `context` variable to rule parameters:
|
83 |
|
84 | ```js
|
85 | function rule(primary, secondary, context) {
|
86 | return (root, result) => {
|
87 | /* .. */
|
88 | };
|
89 | }
|
90 | ```
|
91 |
|
92 | `context` is an object which could have two properties:
|
93 |
|
94 | - `fix`(boolean): If `true`, your rule can apply autofixes.
|
95 | - `newline`(string): Line-ending used in current linted file.
|
96 |
|
97 | If `context.fix` is `true`, then change `root` using PostCSS API and return early before `report()` is called.
|
98 |
|
99 | ```js
|
100 | if (context.fix) {
|
101 | // Apply fixes using PostCSS API
|
102 | return; // Return and don't report a problem
|
103 | }
|
104 |
|
105 | report(/* .. */);
|
106 | ```
|
107 |
|
108 | ### Write tests
|
109 |
|
110 | Each rule must have tests that cover all patterns that:
|
111 |
|
112 | - are considered violations
|
113 | - should _not_ be considered violations
|
114 |
|
115 | Write as many as you can stand to.
|
116 |
|
117 | You should:
|
118 |
|
119 | - test errors in multiple positions, not the same place every time
|
120 | - use realistic (if simple) CSS, and avoid the use of ellipses
|
121 | - use standard CSS syntax by default, and only swap parsers when testing a specific piece of non-standard syntax
|
122 |
|
123 | #### Commonly overlooked edge-cases
|
124 |
|
125 | You should ask yourself how does your rule handle:
|
126 |
|
127 | - variables (`$sass`, `@less` or `var(--custom-property)`)?
|
128 | - CSS strings (e.g. `content: "anything goes";`)?
|
129 | - CSS comments (e.g. `/* anything goes */`)?
|
130 | - `url()` functions, including data URIs (e.g. `url(anything/goes.jpg)`)?
|
131 | - vendor prefixes (e.g. `@-webkit-keyframes name {}`)?
|
132 | - case sensitivity (e.g. `@KEYFRAMES name {}`)?
|
133 | - a pseudo-class _combined_ with a pseudo-element (e.g. `a:hover::before`)?
|
134 | - nesting (e.g. do you resolve `& a {}`, or check it as is?)?
|
135 | - whitespace and punctuation (e.g. comparing `rgb(0,0,0)` with `rgb(0, 0, 0)`)?
|
136 |
|
137 | ### Write the README
|
138 |
|
139 | You should:
|
140 |
|
141 | - only use standard CSS syntax in example code and options
|
142 | - use `<!-- prettier-ignore -->` before `css` code fences
|
143 | - use "this rule" to refer to the rule, e.g. "This rule ignores ..."
|
144 | - align the arrows within the prototypical code example with the beginning of the highlighted construct
|
145 | - align the text within the prototypical code example as far to the left as possible
|
146 |
|
147 | For example:
|
148 |
|
149 |
|
150 | ```css
|
151 | @media screen and (min-width: 768px) {}
|
152 | /** ↑ ↑
|
153 | * These names and values */
|
154 | ```
|
155 |
|
156 | When writing examples, you should use:
|
157 |
|
158 | - complete CSS patterns i.e. avoid ellipses (`...`)
|
159 | - the minimum amount of code possible to communicate the pattern, e.g. if the rule targets selectors then use an empty rule, e.g. `{}`
|
160 | - `{}`, rather than `{ }` for empty rules
|
161 | - the `a` type selector by default
|
162 | - the `@media` at-rules by default
|
163 | - the `color` property by default
|
164 | - _foo_, _bar_ and _baz_ for names, e.g. `.foo`, `#bar`, `--baz`
|
165 |
|
166 | Look at the READMEs of other rules to glean more conventional patterns.
|
167 |
|
168 | ### Wire up the rule
|
169 |
|
170 | The final step is to add references to the new rule in the following places:
|
171 |
|
172 | - [The rules `index.js` file](../../lib/rules/index.js)
|
173 | - [The list of rules](../user-guide/rules/list.md)
|
174 |
|
175 | ## Add an option to a rule
|
176 |
|
177 | You should:
|
178 |
|
179 | 1. Get ready to [contribute code](../../CONTRIBUTING.md#code-contributions).
|
180 | 2. Change the rule's validation to allow for the new option.
|
181 | 3. Add new unit tests to test the option.
|
182 | 4. Add (as little as possible) logic to the rule to make the tests pass.
|
183 | 5. Add documentation about the new option.
|
184 |
|
185 | ## Fix a bug in a rule
|
186 |
|
187 | You should:
|
188 |
|
189 | 1. Get ready to [contribute code](../../CONTRIBUTING.md#code-contributions).
|
190 | 2. Write failing unit tests that exemplify the bug.
|
191 | 3. Fiddle with the rule until those new tests pass.
|
192 |
|
193 | ## Deprecate a rule
|
194 |
|
195 | Deprecating rules doesn't happen very often. When you do, you must:
|
196 |
|
197 | 1. Point the `stylelintReference` link to the specific version of the rule README on the GitHub website, so that it is always accessible.
|
198 | 2. Add the appropriate meta data to mark the rule as deprecated.
|
199 |
|
200 | ## Improve the performance of a rule
|
201 |
|
202 | You can run a benchmarks on any given rule with any valid config using:
|
203 |
|
204 | ```shell
|
205 | npm run benchmark-rule -- ruleName ruleOptions [ruleContext]
|
206 | ```
|
207 |
|
208 | If the `ruleOptions` argument is anything other than a string or a boolean, it must be valid JSON wrapped in quotation marks.
|
209 |
|
210 | ```shell
|
211 | npm run benchmark-rule -- selector-combinator-space-after never
|
212 | ```
|
213 |
|
214 | ```shell
|
215 | npm run benchmark-rule -- selector-combinator-space-after always
|
216 | ```
|
217 |
|
218 | ```shell
|
219 | npm run benchmark-rule -- block-opening-brace-space-before "[\"always\", {\"ignoreAtRules\": [\"else\"]}]"
|
220 | ```
|
221 |
|
222 | If the `ruleContext` argument is specified, the sames procedure would apply:
|
223 |
|
224 | ```shell
|
225 | npm run benchmark-rule -- block-opening-brace-space-before "[\"always\", {\"ignoreAtRules\": [\"else\"]}]" "{\"fix\": \"true\"}"
|
226 | ```
|
227 |
|
228 | The script loads Bootstrap's CSS (from its CDN) and runs it through the configured rule.
|
229 |
|
230 | It will end up printing some simple stats like this:
|
231 |
|
232 | ```shell
|
233 | Warnings: 1441
|
234 | Mean: 74.17598357142856 ms
|
235 | Deviation: 16.63969674310928 ms
|
236 | ```
|
237 |
|
238 | When writing new rules or refactoring existing rules, use these measurements to determine the efficiency of your code.
|
239 |
|
240 | A stylelint rule can repeat its core logic many, many times (e.g. checking every value node of every declaration in a vast CSS codebase). So it's worth paying attention to performance and doing what we can to improve it!
|
241 |
|
242 | **Improving the performance of a rule is a great way to contribute if you want a quick little project.** Try picking a rule and seeing if there's anything you can do to speed it up.
|
243 |
|
244 | Make sure you include benchmark measurements in your pull request!
|