.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / stylelint / docs / developer-guide / plugins.md
1 # Writing plugins
2
3 Plugins are rules and sets of rules built by the community.
4
5 We recommend familiarising yourself and adhering to stylelint's [conventions for writing rules](rules.md), including those for names, options, messages, tests and docs.
6
7 ## The anatomy of a plugin
8
9 ```js
10 // Abbreviated example
11 var stylelint = require("stylelint")
12
13 var ruleName = "plugin/foo-bar"
14 var messages =  stylelint.utils.ruleMessages(ruleName, {
15   expected: "Expected ...",
16 })
17
18 module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {
19   return function(postcssRoot, postcssResult) {
20     var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })
21     if (!validOptions) { return }
22     // ... some logic ...
23     stylelint.utils.report({ .. })
24   }
25 })
26
27 module.exports.ruleName = ruleName
28 module.exports.messages = messages
29 ```
30
31 Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can't think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules. *Make sure you document your plugin's rule name (and namespace) for users, because they will need to use it in their config.*
32
33 `stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules.
34
35 In order for your plugin rule to work with the [standard configuration format](../user-guide/configuration.md#rules), `ruleFunction` should accept 2 arguments: the primary option and, optionally, a secondary options object.
36
37 If your plugin rule supports [autofixing](rules.md#adding-autofixing), then `ruleFunction` should also accept a third argument: context. Also, it's highly recommended 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.
38
39 `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: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You'll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).
40
41 ### Asynchronous rules
42
43 Rules with asynchronous PostCSS plugins are also possible! All you need to do is return a Promise instance from your plugin function.
44
45 ```js
46 // Abbreviated asynchronous example
47 var stylelint = require("stylelint")
48
49 var ruleName = "plugin/foo-bar-async"
50 var messages =  stylelint.utils.ruleMessages(ruleName, {
51   expected: "Expected ...",
52 })
53
54 module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {
55   return function(postcssRoot, postcssResult) {
56     var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })
57     if (!validOptions) { return }
58
59     return new Promise(function(resolve) {
60       // some async operation
61       setTimeout(function() {
62         // ... some logic ...
63         stylelint.utils.report({ .. })
64         resolve()
65       }, 1)
66     })
67   }
68 })
69
70 module.exports.ruleName = ruleName
71 module.exports.messages = messages
72 ```
73
74 ## `stylelint.utils`
75
76 stylelint exposes some utilities that are useful. *For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.*
77
78 ### `stylelint.utils.report`
79
80 Adds violations from your plugin to the list of violations that stylelint will report to the user.
81
82 *Do not use PostCSS's `node.warn()` method directly.* When you use `stylelint.utils.report`, your plugin will respect disabled ranges and other possible future features of stylelint, providing a better user-experience, one that better fits the standard rules.
83
84 ### `stylelint.utils.ruleMessages`
85
86 Tailors your messages to the format of standard stylelint rules.
87
88 ### `stylelint.utils.validateOptions`
89
90 Validates the options for your rule.
91
92 ### `stylelint.utils.checkAgainstRule`
93
94 Checks 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.
95
96 Accepts an options object and a callback that is invoked with warnings from the specified rule. The options are:
97
98 -   `ruleName`: The name of the rule you are invoking.
99 -   `ruleSettings`: Settings for the rule you are invoking, formatting in the same way they would be in a `.stylelintrc` configuration object.
100 -   `root`: The root node to run this rule against.
101
102 Use the warning to create a *new* warning *from your plugin rule* that you report with `stylelint.utils.report`.
103
104 For 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:
105
106 ```js
107 const allowableAtRules = [..]
108
109 function myPluginRule(primaryOption, secondaryOptions) {
110   return (root, result) => {
111     const defaultedOptions = Object.assign({}, secondaryOptions, {
112       ignoreAtRules: allowableAtRules.concat(options.ignoreAtRules || []),
113     })
114
115     stylelint.utils.checkAgainstRule({
116       ruleName: 'at-rule-no-unknown',
117       ruleSettings: [primaryOption, defaultedOptions],
118       root: root
119     }, (warning) => {
120       stylelint.utils.report({
121         message: myMessage,
122         ruleName: myRuleName,
123         result: result,
124         node: warning.node,
125         line: warning.line,
126         column: warning.column,
127       })
128     })
129   }
130 }
131 ```
132
133 ## `stylelint.rules`
134
135 All of the rule functions are available at `stylelint.rules`. This allows you to build on top of existing rules for your particular needs.
136
137 A 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).
138
139 All 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.
140
141 Here's a simple example of a plugin that runs `color-hex-case` only if there is a special directive `@@check-color-hex-case` somewhere in the stylesheet:
142
143 ```js
144 export default stylelint.createPlugin(ruleName, function (expectation) {
145   const runColorHexCase = stylelint.rules["color-hex-case"](expectation)
146   return (root, result) => {
147     if (root.toString().indexOf("@@check-color-hex-case") === -1) return
148     runColorHexCase(root, result)
149   }
150 })
151 ```
152
153 ## Allow primary option arrays
154
155 If 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#primary) doc.
156
157 ## External helper modules
158
159 In 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:
160
161 -   [normalize-selector](https://github.com/getify/normalize-selector): Normalize CSS selectors.
162 -   [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.
163 -   [style-search](https://github.com/davidtheclark/style-search): Search CSS (and CSS-like) strings, with sensitivity to whether matches occur inside strings, comments, and functions.
164
165 Have 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.
166
167 ## Peer dependencies
168
169 You 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.
170
171 For example, to express that your plugin can be used with stylelint versions 7 and 8:
172
173 ```json
174 {
175   "peerDependencies": {
176     "stylelint": "^7.0.0 || ^8.0.0"
177   }
178 }
179 ```
180
181 ## Testing plugins
182
183 For testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).
184
185 ## Plugin packs
186
187 To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).
188
189 ## Sharing plugins and plugin packs
190
191 -   Use the `stylelint-plugin` keyword within your `package.json`.
192 -   Once your plugin is published, please send us a Pull Request to add your plugin to [the list](../user-guide/plugins.md).