]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/developer-guide/nodejs-api.md
import 8.4.0 source
[pve-eslint.git] / eslint / docs / developer-guide / nodejs-api.md
1 # Node.js API
2
3 While ESLint is designed to be run on the command line, it's possible to use ESLint programmatically through the Node.js API. The purpose of the Node.js API is to allow plugin and tool authors to use the ESLint functionality directly, without going through the command line interface.
4
5 **Note:** Use undocumented parts of the API at your own risk. Only those parts that are specifically mentioned in this document are approved for use and will remain stable and reliable. Anything left undocumented is unstable and may change or be removed at any point.
6
7 ## Table of Contents
8
9 * [ESLint]
10 * [constructor()][eslint-constructor]
11 * [lintFiles()][eslint-lintfiles]
12 * [lintText()][eslint-linttext]
13 * [getRulesMetaForResults()][eslint-getrulesmetaforresults]
14 * [calculateConfigForFile()][eslint-calculateconfigforfile]
15 * [isPathIgnored()][eslint-ispathignored]
16 * [loadFormatter()][eslint-loadformatter]
17 * [static version][eslint-version]
18 * [static outputFixes()][eslint-outputfixes]
19 * [static getErrorResults()][eslint-geterrorresults]
20 * [LintResult type][lintresult]
21 * [LintMessage type][lintmessage]
22 * [EditInfo type][editinfo]
23 * [Formatter type][formatter]
24 * [SourceCode](#sourcecode)
25 * [splitLines()](#sourcecodesplitlines)
26 * [Linter](#linter)
27 * [verify()](#linterverify)
28 * [verifyAndFix()](#linterverifyandfix)
29 * [defineRule()](#linterdefinerule)
30 * [defineRules()](#linterdefinerules)
31 * [getRules()](#lintergetrules)
32 * [defineParser()](#linterdefineparser)
33 * [version](#linterversionlinterversion)
34 * [RuleTester](#ruletester)
35 * [Customizing RuleTester](#customizing-ruletester)
36
37 ---
38
39 ## ESLint class
40
41 The `ESLint` class is the primary class to use in Node.js applications.
42
43 This class depends on the Node.js `fs` module and the file system, so you cannot use it in browsers. If you want to lint code on browsers, use the [Linter](#linter) class instead.
44
45 Here's a simple example of using the `ESLint` class:
46
47 ```js
48 const { ESLint } = require("eslint");
49
50 (async function main() {
51 // 1. Create an instance.
52 const eslint = new ESLint();
53
54 // 2. Lint files.
55 const results = await eslint.lintFiles(["lib/**/*.js"]);
56
57 // 3. Format the results.
58 const formatter = await eslint.loadFormatter("stylish");
59 const resultText = formatter.format(results);
60
61 // 4. Output it.
62 console.log(resultText);
63 })().catch((error) => {
64 process.exitCode = 1;
65 console.error(error);
66 });
67 ```
68
69 And here is an example that autofixes lint problems:
70
71 ```js
72 const { ESLint } = require("eslint");
73
74 (async function main() {
75 // 1. Create an instance with the `fix` option.
76 const eslint = new ESLint({ fix: true });
77
78 // 2. Lint files. This doesn't modify target files.
79 const results = await eslint.lintFiles(["lib/**/*.js"]);
80
81 // 3. Modify the files with the fixed code.
82 await ESLint.outputFixes(results);
83
84 // 4. Format the results.
85 const formatter = await eslint.loadFormatter("stylish");
86 const resultText = formatter.format(results);
87
88 // 5. Output it.
89 console.log(resultText);
90 })().catch((error) => {
91 process.exitCode = 1;
92 console.error(error);
93 });
94 ```
95
96 ### ◆ new ESLint(options)
97
98 ```js
99 const eslint = new ESLint(options);
100 ```
101
102 Create a new `ESLint` instance.
103
104 #### Parameters
105
106 The `ESLint` constructor takes an `options` object. If you omit the `options` object then it uses default values for all options. The `options` object has the following properties.
107
108 ##### File Enumeration
109
110 * `options.cwd` (`string`)<br>
111 Default is `process.cwd()`. The working directory. This must be an absolute path.
112 * `options.errorOnUnmatchedPattern` (`boolean`)<br>
113 Default is `true`. Unless set to `false`, the [`eslint.lintFiles()`][eslint-lintfiles] method will throw an error when no target files are found.
114 * `options.extensions` (`string[] | null`)<br>
115 Default is `null`. If you pass directory paths to the [`eslint.lintFiles()`][eslint-lintfiles] method, ESLint checks the files in those directories that have the given extensions. For example, when passing the `src/` directory and `extensions` is `[".js", ".ts"]`, ESLint will lint `*.js` and `*.ts` files in `src/`. If `extensions` is `null`, ESLint checks `*.js` files and files that match `overrides[].files` patterns in your configuration.<br>**Note:** This option only applies when you pass directory paths to the [`eslint.lintFiles()`][eslint-lintfiles] method. If you pass glob patterns like `lib/**/*`, ESLint will lint all files matching the glob pattern regardless of extension.
116 * `options.globInputPaths` (`boolean`)<br>
117 Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't interpret glob patterns.
118 * `options.ignore` (`boolean`)<br>
119 Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't respect `.eslintignore` files or `ignorePatterns` in your configuration.
120 * `options.ignorePath` (`string | null`)<br>
121 Default is `null`. The path to a file ESLint uses instead of `$CWD/.eslintignore`. If a path is present and the file doesn't exist, this constructor will throw an error.
122
123 ##### Linting
124
125 * `options.allowInlineConfig` (`boolean`)<br>
126 Default is `true`. If `false` is present, ESLint suppresses directive comments in source code. If this option is `false`, it overrides the `noInlineConfig` setting in your configurations.
127 * `options.baseConfig` (`ConfigData | null`)<br>
128 Default is `null`. [Configuration object], extended by all configurations used with this instance. You can use this option to define the default settings that will be used if your configuration files don't configure it.
129 * `options.overrideConfig` (`ConfigData | null`)<br>
130 Default is `null`. [Configuration object], overrides all configurations used with this instance. You can use this option to define the settings that will be used even if your configuration files configure it.
131 * `options.overrideConfigFile` (`string | null`)<br>
132 Default is `null`. The path to a configuration file, overrides all configurations used with this instance. The `options.overrideConfig` option is applied after this option is applied.
133 * `options.plugins` (`Record<string, Plugin> | null`)<br>
134 Default is `null`. The plugin implementations that ESLint uses for the `plugins` setting of your configuration. This is a map-like object. Those keys are plugin IDs and each value is implementation.
135 * `options.reportUnusedDisableDirectives` (`"error" | "warn" | "off" | null`)<br>
136 Default is `null`. The severity to report unused eslint-disable directives. If this option is a severity, it overrides the `reportUnusedDisableDirectives` setting in your configurations.
137 * `options.resolvePluginsRelativeTo` (`string` | `null`)<br>
138 Default is `null`. The path to a directory where plugins should be resolved from. If `null` is present, ESLint loads plugins from the location of the configuration file that contains the plugin setting. If a path is present, ESLint loads all plugins from there.
139 * `options.rulePaths` (`string[]`)<br>
140 Default is `[]`. An array of paths to directories to load custom rules from.
141 * `options.useEslintrc` (`boolean`)<br>
142 Default is `true`. If `false` is present, ESLint doesn't load configuration files (`.eslintrc.*` files). Only the configuration of the constructor options is valid.
143
144 ##### Autofix
145
146 * `options.fix` (`boolean | (message: LintMessage) => boolean`)<br>
147 Default is `false`. If `true` is present, the [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods work in autofix mode. If a predicate function is present, the methods pass each lint message to the function, then use only the lint messages for which the function returned `true`.
148 * `options.fixTypes` (`("directive" | "problem" | "suggestion" | "layout")[] | null`)<br>
149 Default is `null`. The types of the rules that the [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods use for autofix.
150
151 ##### Cache-related
152
153 * `options.cache` (`boolean`)<br>
154 Default is `false`. If `true` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method caches lint results and uses it if each target file is not changed. Please mind that ESLint doesn't clear the cache when you upgrade ESLint plugins. In that case, you have to remove the cache file manually. The [`eslint.lintText()`][eslint-linttext] method doesn't use caches even if you pass the `options.filePath` to the method.
155 * `options.cacheLocation` (`string`)<br>
156 Default is `.eslintcache`. The [`eslint.lintFiles()`][eslint-lintfiles] method writes caches into this file.
157 * `options.cacheStrategy` (`string`)<br>
158 Default is `"metadata"`. Strategy for the cache to use for detecting changed files. Can be either `"metadata"` or `"content"`.
159
160 ### ◆ eslint.lintFiles(patterns)
161
162 ```js
163 const results = await eslint.lintFiles(patterns);
164 ```
165
166 This method lints the files that match the glob patterns and then returns the results.
167
168 #### Parameters
169
170 * `patterns` (`string | string[]`)<br>
171 The lint target files. This can contain any of file paths, directory paths, and glob patterns.
172
173 #### Return Value
174
175 * (`Promise<LintResult[]>`)<br>
176 The promise that will be fulfilled with an array of [LintResult] objects.
177
178 ### ◆ eslint.lintText(code, options)
179
180 ```js
181 const results = await eslint.lintText(code, options);
182 ```
183
184 This method lints the given source code text and then returns the results.
185
186 By default, this method uses the configuration that applies to files in the current working directory (the `cwd` constructor option). If you want to use a different configuration, pass `options.filePath`, and ESLint will load the same configuration that [`eslint.lintFiles()`][eslint-lintfiles] would use for a file at `options.filePath`.
187
188 If the `options.filePath` value is configured to be ignored, this method returns an empty array. If the `options.warnIgnored` option is set along with the `options.filePath` option, this method returns a [LintResult] object. In that case, the result may contain a warning that indicates the file was ignored.
189
190 #### Parameters
191
192 The second parameter `options` is omittable.
193
194 * `code` (`string`)<br>
195 The source code text to check.
196 * `options.filePath` (`string`)<br>
197 Optional. The path to the file of the source code text. If omitted, the `result.filePath` becomes the string `"<text>"`.
198 * `options.warnIgnored` (`boolean`)<br>
199 Optional. If `true` is present and the `options.filePath` is a file ESLint should ignore, this method returns a lint result contains a warning message.
200
201 #### Return Value
202
203 * (`Promise<LintResult[]>`)<br>
204 The promise that will be fulfilled with an array of [LintResult] objects. This is an array (despite there being only one lint result) in order to keep the interfaces between this and the [`eslint.lintFiles()`][eslint-lintfiles] method similar.
205
206 ### ◆ eslint.getRulesMetaForResults(results)
207
208 ```js
209 const results = await eslint.lintFiles(patterns);
210 const rulesMeta = eslint.getRulesMetaForResults(results);
211 ```
212
213 This method returns an object containing meta information for each rule that triggered a lint error in the given `results`.
214
215 #### Parameters
216
217 * `results` (`LintResult[]`)<br>
218 An array of [LintResult] objects returned from a call to `ESLint#lintFiles()` or `ESLint#lintText()`.
219
220 #### Return Value
221
222 * (`Object`)<br>
223 An object whose property names are the rule IDs from the `results` and whose property values are the rule's meta information (if available).
224
225 ### ◆ eslint.calculateConfigForFile(filePath)
226
227 ```js
228 const config = await eslint.calculateConfigForFile(filePath);
229 ```
230
231 This method calculates the configuration for a given file, which can be useful for debugging purposes.
232
233 * It resolves and merges `extends` and `overrides` settings into the top level configuration.
234 * It resolves the `parser` setting to absolute paths.
235 * It normalizes the `plugins` setting to align short names. (e.g., `eslint-plugin-foo` → `foo`)
236 * It adds the `processor` setting if a legacy file extension processor is matched.
237 * It doesn't interpret the `env` setting to the `globals` and `parserOptions` settings, so the result object contains the `env` setting as is.
238
239 #### Parameters
240
241 * `filePath` (`string`)<br>
242 The path to the file whose configuration you would like to calculate. Directory paths are forbidden because ESLint cannot handle the `overrides` setting.
243
244 #### Return Value
245
246 * (`Promise<Object>`)<br>
247 The promise that will be fulfilled with a configuration object.
248
249 ### ◆ eslint.isPathIgnored(filePath)
250
251 ```js
252 const isPathIgnored = await eslint.isPathIgnored(filePath);
253 ```
254
255 This method checks if a given file is ignored by your configuration.
256
257 #### Parameters
258
259 * `filePath` (`string`)<br>
260 The path to the file you want to check.
261
262 #### Return Value
263
264 * (`Promise<boolean>`)<br>
265 The promise that will be fulfilled with whether the file is ignored or not. If the file is ignored, then it will return `true`.
266
267 ### ◆ eslint.loadFormatter(nameOrPath)
268
269 ```js
270 const formatter = await eslint.loadFormatter(nameOrPath);
271 ```
272
273 This method loads a formatter. Formatters convert lint results to a human- or machine-readable string.
274
275 #### Parameters
276
277 * `nameOrPath` (`string | undefined`)<br>
278 The path to the file you want to check. The following values are allowed:
279 * `undefined`. In this case, loads the `"stylish"` built-in formatter.
280 * A name of [built-in formatters][builtin-formatters].
281 * A name of [third-party formatters][thirdparty-formatters]. For examples:
282 * `"foo"` will load `eslint-formatter-foo`.
283 * `"@foo"` will load `@foo/eslint-formatter`.
284 * `"@foo/bar"` will load `@foo/eslint-formatter-bar`.
285 * A path to the file that defines a formatter. The path must contain one or more path separators (`/`) in order to distinguish if it's a path or not. For example, start with `./`.
286
287 #### Return Value
288
289 * (`Promise<Formatter>`)<br>
290 The promise that will be fulfilled with a [Formatter] object.
291
292 ### ◆ ESLint.version
293
294 ```js
295 const version = ESLint.version;
296 ```
297
298 The version string of ESLint. E.g. `"7.0.0"`.
299
300 This is a static property.
301
302 ### ◆ ESLint.outputFixes(results)
303
304 ```js
305 await ESLint.outputFixes(results);
306 ```
307
308 This method writes code modified by ESLint's autofix feature into its respective file. If any of the modified files don't exist, this method does nothing.
309
310 This is a static method.
311
312 #### Parameters
313
314 * `results` (`LintResult[]`)<br>
315 The [LintResult] objects to write.
316
317 #### Return Value
318
319 * (`Promise<void>`)<br>
320 The promise that will be fulfilled after all files are written.
321
322 ### ◆ ESLint.getErrorResults(results)
323
324 ```js
325 const filteredResults = ESLint.getErrorResults(results);
326 ```
327
328 This method copies the given results and removes warnings. The returned value contains only errors.
329
330 This is a static method.
331
332 #### Parameters
333
334 * `results` (`LintResult[]`)<br>
335 The [LintResult] objects to filter.
336
337 #### Return Value
338
339 * (`LintResult[]`)<br>
340 The filtered [LintResult] objects.
341
342 ### ◆ LintResult type
343
344 The `LintResult` value is the information of the linting result of each file. The [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods return it. It has the following properties:
345
346 * `filePath` (`string`)<br>
347 The absolute path to the file of this result. This is the string `"<text>"` if the file path is unknown (when you didn't pass the `options.filePath` option to the [`eslint.lintText()`][eslint-linttext] method).
348 * `messages` (`LintMessage[]`)<br>
349 The array of [LintMessage] objects.
350 * `fixableErrorCount` (`number`)<br>
351 The number of errors that can be fixed automatically by the `fix` constructor option.
352 * `fixableWarningCount` (`number`)<br>
353 The number of warnings that can be fixed automatically by the `fix` constructor option.
354 * `errorCount` (`number`)<br>
355 The number of errors. This includes fixable errors and fatal errors.
356 * `fatalErrorCount` (`number`)<br>
357 The number of fatal errors.
358 * `warningCount` (`number`)<br>
359 The number of warnings. This includes fixable warnings.
360 * `output` (`string | undefined`)<br>
361 The modified source code text. This property is undefined if any fixable messages didn't exist.
362 * `source` (`string | undefined`)<br>
363 The original source code text. This property is undefined if any messages didn't exist or the `output` property exists.
364 * `usedDeprecatedRules` (`{ ruleId: string; replacedBy: string[] }[]`)<br>
365 The information about the deprecated rules that were used to check this file.
366
367 ### ◆ LintMessage type
368
369 The `LintMessage` value is the information of each linting error. The `messages` property of the [LintResult] type contains it. It has the following properties:
370
371 * `ruleId` (`string` | `null`)<br>
372 The rule name that generates this lint message. If this message is generated by the ESLint core rather than rules, this is `null`.
373 * `severity` (`1 | 2`)<br>
374 The severity of this message. `1` means warning and `2` means error.
375 * `fatal` (`boolean | undefined`)<br>
376 `true` if this is a fatal error unrelated to a rule, like a parsing error.
377 * `message` (`string`)<br>
378 The error message.
379 * `line` (`number | undefined`)<br>
380 The 1-based line number of the begin point of this message.
381 * `column` (`number | undefined`)<br>
382 The 1-based column number of the begin point of this message.
383 * `endLine` (`number | undefined`)<br>
384 The 1-based line number of the end point of this message. This property is undefined if this message is not a range.
385 * `endColumn` (`number | undefined`)<br>
386 The 1-based column number of the end point of this message. This property is undefined if this message is not a range.
387 * `fix` (`EditInfo | undefined`)<br>
388 The [EditInfo] object of autofix. This property is undefined if this message is not fixable.
389 * `suggestions` (`{ desc: string; fix: EditInfo }[] | undefined`)<br>
390 The list of suggestions. Each suggestion is the pair of a description and an [EditInfo] object to fix code. API users such as editor integrations can choose one of them to fix the problem of this message. This property is undefined if this message doesn't have any suggestions.
391
392 ### ◆ EditInfo type
393
394 The `EditInfo` value is information to edit text. The `fix` and `suggestions` properties of [LintMessage] type contain it. It has following properties:
395
396 * `range` (`[number, number]`)<br>
397 The pair of 0-based indices in source code text to remove.
398 * `text` (`string`)<br>
399 The text to add.
400
401 This edit information means replacing the range of the `range` property by the `text` property value. It's like `sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1])`. Therefore, it's an add if the `range[0]` and `range[1]` property values are the same value, and it's removal if the `text` property value is empty string.
402
403 ### ◆ Formatter type
404
405 The `Formatter` value is the object to convert the [LintResult] objects to text. The [eslint.loadFormatter()][eslint-loadformatter] method returns it. It has the following method:
406
407 * `format` (`(results: LintResult[]) => string | Promise<string>`)<br>
408 The method to convert the [LintResult] objects to text.
409
410 ---
411
412 ## SourceCode
413
414 The `SourceCode` type represents the parsed source code that ESLint executes on. It's used internally in ESLint and is also available so that already-parsed code can be used. You can create a new instance of `SourceCode` by passing in the text string representing the code and an abstract syntax tree (AST) in [ESTree](https://github.com/estree/estree) format (including location information, range information, comments, and tokens):
415
416 ```js
417 const SourceCode = require("eslint").SourceCode;
418
419 const code = new SourceCode("var foo = bar;", ast);
420 ```
421
422 The `SourceCode` constructor throws an error if the AST is missing any of the required information.
423
424 The `SourceCode` constructor strips Unicode BOM.
425 Please note the AST also should be parsed from stripped text.
426
427 ```js
428 const SourceCode = require("eslint").SourceCode;
429
430 const code = new SourceCode("\uFEFFvar foo = bar;", ast);
431
432 assert(code.hasBOM === true);
433 assert(code.text === "var foo = bar;");
434 ```
435
436 ### SourceCode#splitLines()
437
438 This is a static function on `SourceCode` that is used to split the source code text into an array of lines.
439
440 ```js
441 const SourceCode = require("eslint").SourceCode;
442
443 const code = "var a = 1;\nvar b = 2;"
444
445 // split code into an array
446 const codeLines = SourceCode.splitLines(code);
447
448 /*
449 Value of codeLines will be
450 [
451 "var a = 1;",
452 "var b = 2;"
453 ]
454 */
455 ```
456
457 ---
458
459 ## Linter
460
461 The `Linter` object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it simply parses and reports on the code. In particular, the `Linter` object does not process configuration objects or files. Unless you are working in the browser, you probably want to use the [ESLint class](#eslint-class) class instead.
462
463 The `Linter` is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:
464
465 * `cwd` - Path to a directory that should be considered as the current working directory. It is accessible to rules by calling `context.getCwd()` (see [The Context Object](./working-with-rules.md#the-context-object)). If `cwd` is `undefined`, it will be normalized to `process.cwd()` if the global `process` object is defined (for example, in the Node.js runtime) , or `undefined` otherwise.
466
467 For example:
468
469 ```js
470 const Linter = require("eslint").Linter;
471 const linter1 = new Linter({ cwd: 'path/to/project' });
472 const linter2 = new Linter();
473 ```
474
475 In this example, rules run on `linter1` will get `path/to/project` when calling `context.getCwd()`.
476 Those run on `linter2` will get `process.cwd()` if the global `process` object is defined or `undefined` otherwise (e.g. on the browser <https://eslint.org/demo>).
477
478 ### Linter#verify
479
480 The most important method on `Linter` is `verify()`, which initiates linting of the given text. This method accepts three arguments:
481
482 * `code` - the source code to lint (a string or instance of `SourceCode`).
483 * `config` - a configuration object that has been processed and normalized by `ESLint` using eslintrc files and/or other configuration arguments.
484 * **Note**: If you want to lint text and have your configuration be read and processed, use [`ESLint#lintFiles()`][eslint-lintfiles] or [`ESLint#lintText()`][eslint-linttext] instead.
485 * `options` - (optional) Additional options for this run.
486 * `filename` - (optional) the filename to associate with the source code.
487 * `preprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `preprocess` method.
488 * `postprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `postprocess` method.
489 * `filterCodeBlock` - (optional) A function that decides which code blocks the linter should adopt. The function receives two arguments. The first argument is the virtual filename of a code block. The second argument is the text of the code block. If the function returned `true` then the linter adopts the code block. If the function was omitted, the linter adopts only `*.js` code blocks. If you provided a `filterCodeBlock` function, it overrides this default behavior, so the linter doesn't adopt `*.js` code blocks automatically.
490 * `disableFixes` - (optional) when set to `true`, the linter doesn't make either the `fix` or `suggestions` property of the lint result.
491 * `allowInlineConfig` - (optional) set to `false` to disable inline comments from changing ESLint rules.
492 * `reportUnusedDisableDirectives` - (optional) when set to `true`, adds reported errors for unused `eslint-disable` directives when no problems would be reported in the disabled area anyway.
493
494 If the third argument is a string, it is interpreted as the `filename`.
495
496 You can call `verify()` like this:
497
498 ```js
499 const Linter = require("eslint").Linter;
500 const linter = new Linter();
501
502 const messages = linter.verify("var foo;", {
503 rules: {
504 semi: 2
505 }
506 }, { filename: "foo.js" });
507
508 // or using SourceCode
509
510 const Linter = require("eslint").Linter,
511 linter = new Linter(),
512 SourceCode = require("eslint").SourceCode;
513
514 const code = new SourceCode("var foo = bar;", ast);
515
516 const messages = linter.verify(code, {
517 rules: {
518 semi: 2
519 }
520 }, { filename: "foo.js" });
521 ```
522
523 The `verify()` method returns an array of objects containing information about the linting warnings and errors. Here's an example:
524
525 ```js
526 {
527 fatal: false,
528 ruleId: "semi",
529 severity: 2,
530 line: 1,
531 column: 23,
532 message: "Expected a semicolon.",
533 fix: {
534 range: [1, 15],
535 text: ";"
536 }
537 }
538 ```
539
540 The information available for each linting message is:
541
542 * `column` - the column on which the error occurred.
543 * `fatal` - usually omitted, but will be set to true if there's a parsing error (not related to a rule).
544 * `line` - the line on which the error occurred.
545 * `message` - the message that should be output.
546 * `nodeType` - the node or token type that was reported with the problem.
547 * `ruleId` - the ID of the rule that triggered the messages (or null if `fatal` is true).
548 * `severity` - either 1 or 2, depending on your configuration.
549 * `endColumn` - the end column of the range on which the error occurred (this property is omitted if it's not range).
550 * `endLine` - the end line of the range on which the error occurred (this property is omitted if it's not range).
551 * `fix` - an object describing the fix for the problem (this property is omitted if no fix is available).
552 * `suggestions` - an array of objects describing possible lint fixes for editors to programmatically enable (see details in the [Working with Rules docs](./working-with-rules.md#providing-suggestions)).
553
554 Linting message objects have a deprecated `source` property. This property **will be removed** from linting messages in an upcoming breaking release. If you depend on this property, you should now use the `SourceCode` instance provided by the linter.
555
556 You can also get an instance of the `SourceCode` object used inside of `linter` by using the `getSourceCode()` method:
557
558 ```js
559 const Linter = require("eslint").Linter;
560 const linter = new Linter();
561
562 const messages = linter.verify("var foo = bar;", {
563 rules: {
564 semi: 2
565 }
566 }, { filename: "foo.js" });
567
568 const code = linter.getSourceCode();
569
570 console.log(code.text); // "var foo = bar;"
571 ```
572
573 In this way, you can retrieve the text and AST used for the last run of `linter.verify()`.
574
575 ### Linter#verifyAndFix()
576
577 This method is similar to verify except that it also runs autofixing logic, similar to the `--fix` flag on the command line. The result object will contain the autofixed code, along with any remaining linting messages for the code that were not autofixed.
578
579 ```js
580 const Linter = require("eslint").Linter;
581 const linter = new Linter();
582
583 const messages = linter.verifyAndFix("var foo", {
584 rules: {
585 semi: 2
586 }
587 });
588 ```
589
590 Output object from this method:
591
592 ```js
593 {
594 fixed: true,
595 output: "var foo;",
596 messages: []
597 }
598 ```
599
600 The information available is:
601
602 * `fixed` - True, if the code was fixed.
603 * `output` - Fixed code text (might be the same as input if no fixes were applied).
604 * `messages` - Collection of all messages for the given code (It has the same information as explained above under `verify` block).
605
606 ### Linter#defineRule
607
608 Each `Linter` instance holds a map of rule names to loaded rule objects. By default, all ESLint core rules are loaded. If you want to use `Linter` with custom rules, you should use the `defineRule` method to register your rules by ID.
609
610 ```js
611 const Linter = require("eslint").Linter;
612 const linter = new Linter();
613
614 linter.defineRule("my-custom-rule", {
615 // (an ESLint rule)
616
617 create(context) {
618 // ...
619 }
620 });
621
622 const results = linter.verify("// some source text", { rules: { "my-custom-rule": "error" } });
623 ```
624
625 ### Linter#defineRules
626
627 This is a convenience method similar to `Linter#defineRule`, except that it allows you to define many rules at once using an object.
628
629 ```js
630 const Linter = require("eslint").Linter;
631 const linter = new Linter();
632
633 linter.defineRules({
634 "my-custom-rule": { /* an ESLint rule */ create() {} },
635 "another-custom-rule": { /* an ESLint rule */ create() {} }
636 });
637
638 const results = linter.verify("// some source text", {
639 rules: {
640 "my-custom-rule": "error",
641 "another-custom-rule": "warn"
642 }
643 });
644 ```
645
646 ### Linter#getRules
647
648 This method returns a map of all loaded rules.
649
650 ```js
651 const Linter = require("eslint").Linter;
652 const linter = new Linter();
653
654 linter.getRules();
655
656 /*
657 Map {
658 'accessor-pairs' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
659 'array-bracket-newline' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
660 ...
661 }
662 */
663 ```
664
665 ### Linter#defineParser
666
667 Each instance of `Linter` holds a map of custom parsers. If you want to define a parser programmatically, you can add this function
668 with the name of the parser as first argument and the [parser object](/docs/developer-guide/working-with-custom-parsers.md) as second argument. The default `"espree"` parser will already be loaded for every `Linter` instance.
669
670 ```js
671 const Linter = require("eslint").Linter;
672 const linter = new Linter();
673
674 linter.defineParser("my-custom-parser", {
675 parse(code, options) {
676 // ...
677 }
678 });
679
680 const results = linter.verify("// some source text", { parser: "my-custom-parser" });
681 ```
682
683 ### Linter#version/Linter.version
684
685 Each instance of `Linter` has a `version` property containing the semantic version number of ESLint that the `Linter` instance is from.
686
687 ```js
688 const Linter = require("eslint").Linter;
689 const linter = new Linter();
690
691 linter.version; // => '4.5.0'
692 ```
693
694 There is also a `Linter.version` property that you can read without instantiating `Linter`:
695
696 ```js
697 const Linter = require("eslint").Linter;
698
699 Linter.version; // => '4.5.0'
700 ```
701
702 ---
703
704 ## RuleTester
705
706 `eslint.RuleTester` is a utility to write tests for ESLint rules. It is used internally for the bundled rules that come with ESLint, and it can also be used by plugins.
707
708 Example usage:
709
710 ```js
711 "use strict";
712
713 const rule = require("../../../lib/rules/my-rule"),
714 RuleTester = require("eslint").RuleTester;
715
716 const ruleTester = new RuleTester();
717
718 ruleTester.run("my-rule", rule, {
719 valid: [
720 {
721 code: "var foo = true",
722 options: [{ allowFoo: true }]
723 }
724 ],
725
726 invalid: [
727 {
728 code: "var invalidVariable = true",
729 errors: [{ message: "Unexpected invalid variable." }]
730 },
731 {
732 code: "var invalidVariable = true",
733 errors: [{ message: /^Unexpected.+variable/ }]
734 }
735 ]
736 });
737 ```
738
739 The `RuleTester` constructor accepts an optional object argument, which can be used to specify defaults for your test cases. For example, if all of your test cases use ES2015, you can set it as a default:
740
741 ```js
742 const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } });
743 ```
744
745 The `RuleTester#run()` method is used to run the tests. It should be passed the following arguments:
746
747 * The name of the rule (string)
748 * The rule object itself (see ["working with rules"](./working-with-rules))
749 * An object containing `valid` and `invalid` properties, each of which is an array containing test cases.
750
751 A test case is an object with the following properties:
752
753 * `name` (string, optional): The name to use for the test case, to make it easier to find
754 * `code` (string, required): The source code that the rule should be run on
755 * `options` (array, optional): The options passed to the rule. The rule severity should not be included in this list.
756 * `filename` (string, optional): The filename for the given case (useful for rules that make assertions about filenames).
757 * `only` (boolean, optional): Run this case exclusively for debugging in supported test frameworks.
758
759 In addition to the properties above, invalid test cases can also have the following properties:
760
761 * `errors` (number or array, required): Asserts some properties of the errors that the rule is expected to produce when run on this code. If this is a number, asserts the number of errors produced. Otherwise, this should be a list of objects, each containing information about a single reported error. The following properties can be used for an error (all are optional):
762 * `message` (string/regexp): The message for the error
763 * `messageId` (string): The Id for the error. See [testing errors with messageId](#testing-errors-with-messageid) for details
764 * `data` (object): Placeholder data which can be used in combination with `messageId`
765 * `type` (string): The type of the reported AST node
766 * `line` (number): The 1-based line number of the reported location
767 * `column` (number): The 1-based column number of the reported location
768 * `endLine` (number): The 1-based line number of the end of the reported location
769 * `endColumn` (number): The 1-based column number of the end of the reported location
770 * `suggestions` (array): An array of objects with suggestion details to check. See [Testing Suggestions](#testing-suggestions) for details
771
772 If a string is provided as an error instead of an object, the string is used to assert the `message` of the error.
773 * `output` (string, required if the rule fixes code): Asserts the output that will be produced when using this rule for a single pass of autofixing (e.g. with the `--fix` command line flag). If this is `null`, asserts that none of the reported problems suggest autofixes.
774
775 Any additional properties of a test case will be passed directly to the linter as config options. For example, a test case can have a `parserOptions` property to configure parser behavior:
776
777 ```js
778 {
779 code: "let foo;",
780 parserOptions: { ecmaVersion: 2015 }
781 }
782 ```
783
784 If a valid test case only uses the `code` property, it can optionally be provided as a string containing the code, rather than an object with a `code` key.
785
786 ### Testing errors with `messageId`
787
788 If the rule under test uses `messageId`s, you can use `messageId` property in a test case to assert reported error's `messageId` instead of its `message`.
789
790 ```js
791 {
792 code: "let foo;",
793 errors: [{ messageId: "unexpected" }]
794 }
795 ```
796
797 For messages with placeholders, a test case can also use `data` property to additionally assert reported error's `message`.
798
799 ```js
800 {
801 code: "let foo;",
802 errors: [{ messageId: "unexpected", data: { name: "foo" } }]
803 }
804 ```
805
806 Please note that `data` in a test case does not assert `data` passed to `context.report`. Instead, it is used to form the expected message text which is then compared with the received `message`.
807
808 ### Testing Suggestions
809
810 Suggestions can be tested by defining a `suggestions` key on an errors object. The options to check for the suggestions are the following (all are optional):
811
812 * `desc` (string): The suggestion `desc` value
813 * `messageId` (string): The suggestion `messageId` value for suggestions that use `messageId`s
814 * `data` (object): Placeholder data which can be used in combination with `messageId`
815 * `output` (string): A code string representing the result of applying the suggestion fix to the input code
816
817 Example:
818
819 ```js
820 ruleTester.run("my-rule-for-no-foo", rule, {
821 valid: [],
822 invalid: [{
823 code: "var foo;",
824 errors: [{
825 suggestions: [{
826 desc: "Rename identifier 'foo' to 'bar'",
827 output: "var bar;"
828 }]
829 }]
830 }]
831 })
832 ```
833
834 `messageId` and `data` properties in suggestion test objects work the same way as in error test objects. See [testing errors with messageId](#testing-errors-with-messageid) for details.
835
836 ```js
837 ruleTester.run("my-rule-for-no-foo", rule, {
838 valid: [],
839 invalid: [{
840 code: "var foo;",
841 errors: [{
842 suggestions: [{
843 messageId: "renameFoo",
844 data: { newName: "bar" },
845 output: "var bar;"
846 }]
847 }]
848 }]
849 })
850 ```
851
852 ### Customizing RuleTester
853
854 `RuleTester` depends on two functions to run tests: `describe` and `it`. These functions can come from various places:
855
856 1. If `RuleTester.describe` and `RuleTester.it` have been set to function values, `RuleTester` will use `RuleTester.describe` and `RuleTester.it` to run tests. You can use this to customize the behavior of `RuleTester` to match a test framework that you're using.
857
858 If `RuleTester.itOnly` has been set to a function value, `RuleTester` will call `RuleTester.itOnly` instead of `RuleTester.it` to run cases with `only: true`. If `RuleTester.itOnly` is not set but `RuleTester.it` has an `only` function property, `RuleTester` will fall back to `RuleTester.it.only`.
859
860 2. Otherwise, if `describe` and `it` are present as globals, `RuleTester` will use `global.describe` and `global.it` to run tests and `global.it.only` to run cases with `only: true`. This allows `RuleTester` to work when using frameworks like [Mocha](https://mochajs.org/) without any additional configuration.
861 3. Otherwise, `RuleTester#run` will simply execute all of the tests in sequence, and will throw an error if one of them fails. This means you can simply execute a test file that calls `RuleTester.run` using `Node.js`, without needing a testing framework.
862
863 `RuleTester#run` calls the `describe` function with two arguments: a string describing the rule, and a callback function. The callback calls the `it` function with a string describing the test case, and a test function. The test function will return successfully if the test passes, and throw an error if the test fails. The signature for `only` is the same as `it`. `RuleTester` calls either `it` or `only` for every case even when some cases have `only: true`, and the test framework is responsible for implementing test case exclusivity. (Note that this is the standard behavior for test suites when using frameworks like [Mocha](https://mochajs.org/); this information is only relevant if you plan to customize `RuleTester.describe`, `RuleTester.it`, or `RuleTester.itOnly`.)
864
865 Example of customizing `RuleTester`:
866
867 ```js
868 "use strict";
869
870 const RuleTester = require("eslint").RuleTester,
871 test = require("my-test-runner"),
872 myRule = require("../../../lib/rules/my-rule");
873
874 RuleTester.describe = function(text, method) {
875 RuleTester.it.title = text;
876 return method.call(this);
877 };
878
879 RuleTester.it = function(text, method) {
880 test(RuleTester.it.title + ": " + text, method);
881 };
882
883 // then use RuleTester as documented
884
885 const ruleTester = new RuleTester();
886
887 ruleTester.run("my-rule", myRule, {
888 valid: [
889 // valid test cases
890 ],
891 invalid: [
892 // invalid test cases
893 ]
894 })
895 ```
896
897 ---
898
899 [configuration object]: ../user-guide/configuring
900 [builtin-formatters]: https://eslint.org/docs/user-guide/formatters/
901 [thirdparty-formatters]: https://www.npmjs.com/search?q=eslintformatter
902 [eslint]: #eslint-class
903 [eslint-constructor]: #-new-eslintoptions
904 [eslint-lintfiles]: #-eslintlintfilespatterns
905 [eslint-linttext]: #-eslintlinttextcode-options
906 [eslint-getrulesmetaforresults]: #-eslintgetrulesmetaforresultsresults
907 [eslint-calculateconfigforfile]: #-eslintcalculateconfigforfilefilepath
908 [eslint-ispathignored]: #-eslintispathignoredfilepath
909 [eslint-loadformatter]: #-eslintloadformatternameorpath
910 [eslint-version]: #-eslintversion
911 [eslint-outputfixes]: #-eslintoutputfixesresults
912 [eslint-geterrorresults]: #-eslintgeterrorresultsresults
913 [lintresult]: #-lintresult-type
914 [lintmessage]: #-lintmessage-type
915 [editinfo]: #-editinfo-type
916 [formatter]: #-formatter-type
917 [linter]: #linter