]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/developer-guide/nodejs-api.md
import 7.12.1 upstream release
[pve-eslint.git] / eslint / docs / developer-guide / nodejs-api.md
CommitLineData
eb39fafa
DC
1# Node.js API
2
3While 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
56c4a2cb
DC
9* [ESLint]
10 * [constructor()][eslint-constructor]
6f036462
TL
11 * [lintFiles()][eslint-lintfiles]
12 * [lintText()][eslint-linttext]
13 * [calculateConfigForFile()][eslint-calculateconfigforfile]
14 * [isPathIgnored()][eslint-ispathignored]
15 * [loadFormatter()][eslint-loadformatter]
56c4a2cb 16 * [static version][eslint-version]
6f036462
TL
17 * [static outputFixes()][eslint-outputfixes]
18 * [static getErrorResults()][eslint-geterrorresults]
19 * [LintResult type][lintresult]
20 * [LintMessage type][lintmessage]
21 * [EditInfo type][editinfo]
22 * [Formatter type][formatter]
eb39fafa
DC
23* [SourceCode](#sourcecode)
24 * [splitLines()](#sourcecode-splitlines)
25* [Linter](#linter)
26 * [verify()](#linter-verify)
27 * [verifyAndFix()](#linter-verifyandfix)
28 * [defineRule()](#linter-definerule)
29 * [defineRules()](#linter-definerules)
30 * [getRules()](#linter-getrules)
31 * [defineParser()](#linter-defineparser)
32 * [version](#linter-version)
33* [linter (deprecated)](#linter-1)
56c4a2cb 34* [CLIEngine (deprecated)](#cliengine)
eb39fafa
DC
35* [RuleTester](#ruletester)
36 * [Customizing RuleTester](#customizing-ruletester)
37* [Deprecated APIs](#deprecated-apis)
38
56c4a2cb
DC
39---
40
41## ESLint class
42
43The `ESLint` class is the primary class to use in Node.js applications.
44
45This 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.
46
47Here's a simple example of using the `ESLint` class:
48
49```js
50const { ESLint } = require("eslint");
51
52(async function main() {
53 // 1. Create an instance.
54 const eslint = new ESLint();
55
56 // 2. Lint files.
57 const results = await eslint.lintFiles(["lib/**/*.js"]);
58
59 // 3. Format the results.
60 const formatter = await eslint.loadFormatter("stylish");
61 const resultText = formatter.format(results);
62
63 // 4. Output it.
64 console.log(resultText);
65})().catch((error) => {
66 process.exitCode = 1;
67 console.error(error);
68});
69```
70
71And here is an example that autofixes lint problems:
72
73```js
74const { ESLint } = require("eslint");
75
76(async function main() {
77 // 1. Create an instance with the `fix` option.
78 const eslint = new ESLint({ fix: true });
79
80 // 2. Lint files. This doesn't modify target files.
81 const results = await eslint.lintFiles(["lib/**/*.js"]);
82
83 // 3. Modify the files with the fixed code.
84 await ESLint.outputFixes(results);
85
86 // 4. Format the results.
87 const formatter = await eslint.loadFormatter("stylish");
88 const resultText = formatter.format(results);
89
90 // 5. Output it.
91 console.log(resultText);
92})().catch((error) => {
93 process.exitCode = 1;
94 console.error(error);
95});
96```
97
98### ◆ new ESLint(options)
99
100```js
101const eslint = new ESLint(options);
102```
103
104Create a new `ESLint` instance.
105
106#### Parameters
107
108The `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.
109
110##### File Enumeration
111
112* `options.cwd` (`string`)<br>
113 Default is `process.cwd()`. The working directory. This must be an absolute path.
114* `options.errorOnUnmatchedPattern` (`boolean`)<br>
115 Default is `true`. Unless set to `false`, the [`eslint.lintFiles()`][eslint-lintfiles] method will throw an error when no target files are found.
116* `options.extensions` (`string[] | null`)<br>
117 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.
118* `options.globInputPaths` (`boolean`)<br>
119 Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't interpret glob patterns.
120* `options.ignore` (`boolean`)<br>
121 Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't respect `.eslintignore` files or `ignorePatterns` in your configuration.
122* `options.ignorePath` (`string | null`)<br>
123 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.
124
125##### Linting
126
127* `options.allowInlineConfig` (`boolean`)<br>
128 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.
129* `options.baseConfig` (`ConfigData | null`)<br>
130 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.
131* `options.overrideConfig` (`ConfigData | null`)<br>
132 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.
133* `options.overrideConfigFile` (`string | null`)<br>
134 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.
135* `options.plugins` (`Record<string, Plugin> | null`)<br>
136 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.
137* `options.reportUnusedDisableDirectives` (`"error" | "warn" | "off" | null`)<br>
138 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.
139* `options.resolvePluginsRelativeTo` (`string` | `null`)<br>
140 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.
141* `options.rulePaths` (`string[]`)<br>
142 Default is `[]`. An array of paths to directories to load custom rules from.
143* `options.useEslintrc` (`boolean`)<br>
144 Default is `true`. If `false` is present, ESLint doesn't load configuration files (`.eslintrc.*` files). Only the configuration of the constructor options is valid.
145
146##### Autofix
147
148* `options.fix` (`boolean | (message: LintMessage) => boolean`)<br>
149 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`.
150* `options.fixTypes` (`("problem" | "suggestion" | "layout")[] | null`)<br>
151 Default is `null`. The types of the rules that the [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods use for autofix.
152
153##### Cache-related
154
155* `options.cache` (`boolean`)<br>
156 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.
157* `options.cacheLocation` (`string`)<br>
158 Default is `.eslintcache`. The [`eslint.lintFiles()`][eslint-lintfiles] method writes caches into this file.
159
160### ◆ eslint.lintFiles(patterns)
161
162```js
163const results = await eslint.lintFiles(patterns);
164```
165
166This 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
181const results = await eslint.lintText(code, options);
182```
183
184This method lints the given source code text and then returns the results.
185
186By 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
188If 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
192The 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.calculateConfigForFile(filePath)
207
208```js
209const config = await eslint.calculateConfigForFile(filePath);
210```
211
212This method calculates the configuration for a given file, which can be useful for debugging purposes.
213
214* It resolves and merges `extends` and `overrides` settings into the top level configuration.
215* It resolves the `parser` setting to absolute paths.
216* It normalizes the `plugins` setting to align short names. (e.g., `eslint-plugin-foo` → `foo`)
217* It adds the `processor` setting if a legacy file extension processor is matched.
218* It doesn't interpret the `env` setting to the `globals` and `parserOptions` settings, so the result object contains the `env` setting as is.
219
220#### Parameters
221
222* `filePath` (`string`)<br>
223 The path to the file whose configuration you would like to calculate. Directory paths are forbidden because ESLint cannot handle the `overrides` setting.
224
225#### Return Value
226
227* (`Promise<Object>`)<br>
228 The promise that will be fulfilled with a configuration object.
229
230### ◆ eslint.isPathIgnored(filePath)
231
232```js
233const isPathIgnored = await eslint.isPathIgnored(filePath);
234```
235
236This method checks if a given file is ignored by your configuration.
237
238#### Parameters
239
240* `filePath` (`string`)<br>
241 The path to the file you want to check.
242
243#### Return Value
244
245* (`Promise<boolean>`)<br>
246 The promise that will be fulfilled with whether the file is ignored or not. If the file is ignored, then it will return `true`.
247
248### ◆ eslint.loadFormatter(nameOrPath)
249
250```js
251const formatter = await eslint.loadFormatter(nameOrPath);
252```
253
254This method loads a formatter. Formatters convert lint results to a human- or machine-readable string.
255
256#### Parameters
257
258* `nameOrPath` (`string | undefined`)<br>
259 The path to the file you want to check. The following values are allowed:
260 * `undefined`. In this case, loads the `"stylish"` built-in formatter.
261 * A name of [built-in formatters][builtin-formatters].
262 * A name of [third-party formatters][thirdparty-formatters]. For examples:
263 * `"foo"` will load `eslint-formatter-foo`.
264 * `"@foo"` will load `@foo/eslint-formatter`.
265 * `"@foo/bar"` will load `@foo/eslint-formatter-bar`.
266 * 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 `./`.
267
268#### Return Value
269
270* (`Promise<Formatter>`)<br>
271 The promise that will be fulfilled with a [Formatter] object.
272
273### ◆ ESLint.version
274
275```js
276const version = ESLint.version;
277```
278
279The version string of ESLint. E.g. `"7.0.0"`.
280
281This is a static property.
282
283### ◆ ESLint.outputFixes(results)
284
285```js
286await ESLint.outputFixes(results);
287```
288
289This 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.
290
291This is a static method.
292
293#### Parameters
294
295* `results` (`LintResult[]`)<br>
296 The [LintResult] objects to write.
297
298#### Return Value
299
300* (`Promise<void>`)<br>
301 The promise that will be fulfilled after all files are written.
302
303### ◆ ESLint.getErrorResults(results)
304
305```js
306const filteredResults = ESLint.getErrorResults(results);
307```
308
309This method copies the given results and removes warnings. The returned value contains only errors.
310
311This is a static method.
312
313#### Parameters
314
315* `results` (`LintResult[]`)<br>
316 The [LintResult] objects to filter.
317
318#### Return Value
319
320* (`LintResult[]`)<br>
321 The filtered [LintResult] objects.
322
323### ◆ LintResult type
324
325The `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:
326
327* `filePath` (`string`)<br>
328 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).
329* `messages` (`LintMessage[]`)<br>
330 The array of [LintMessage] objects.
331* `fixableErrorCount` (`number`)<br>
332 The number of errors that can be fixed automatically by the `fix` constructor option.
333* `fixableWarningCount` (`number`)<br>
334 The number of warnings that can be fixed automatically by the `fix` constructor option.
335* `errorCount` (`number`)<br>
336 The number of errors. This includes fixable errors.
337* `warningCount` (`number`)<br>
338 The number of warnings. This includes fixable warnings.
339* `output` (`string | undefined`)<br>
340 The modified source code text. This property is undefined if any fixable messages didn't exist.
341* `source` (`string | undefined`)<br>
342 The original source code text. This property is undefined if any messages didn't exist or the `output` property exists.
343* `usedDeprecatedRules` (`{ ruleId: string; replacedBy: string[] }[]`)<br>
344 The information about the deprecated rules that were used to check this file.
345
346### ◆ LintMessage type
347
348The `LintMessage` value is the information of each linting error. The `messages` property of the [LintResult] type contains it. It has the following properties:
349
350* `ruleId` (`string` | `null`)<br>
351 The rule name that generates this lint message. If this message is generated by the ESLint core rather than rules, this is `null`.
352* `severity` (`1 | 2`)<br>
353 The severity of this message. `1` means warning and `2` means error.
354* `message` (`string`)<br>
355 The error message.
356* `line` (`number`)<br>
357 The 1-based line number of the begin point of this message.
358* `column` (`number`)<br>
359 The 1-based column number of the begin point of this message.
360* `endLine` (`number | undefined`)<br>
361 The 1-based line number of the end point of this message. This property is undefined if this message is not a range.
362* `endColumn` (`number | undefined`)<br>
363 The 1-based column number of the end point of this message. This property is undefined if this message is not a range.
364* `fix` (`EditInfo | undefined`)<br>
365 The [EditInfo] object of autofix. This property is undefined if this message is not fixable.
366* `suggestions` (`{ desc: string; fix: EditInfo }[] | undefined`)<br>
367 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.
368
369### ◆ EditInfo type
370
371The `EditInfo` value is information to edit text. The `fix` and `suggestions` properties of [LintMessage] type contain it. It has following properties:
372
373* `range` (`[number, number]`)<br>
374 The pair of 0-based indices in source code text to remove.
375* `text` (`string`)<br>
376 The text to add.
377
378This 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.
379
380### ◆ Formatter type
381
382The `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:
383
384* `format` (`(results: LintResult[]) => string`)<br>
385 The method to convert the [LintResult] objects to text.
386
387---
388
eb39fafa
DC
389## SourceCode
390
391The `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):
392
393```js
394const SourceCode = require("eslint").SourceCode;
395
396const code = new SourceCode("var foo = bar;", ast);
397```
398
399The `SourceCode` constructor throws an error if the AST is missing any of the required information.
400
401The `SourceCode` constructor strips Unicode BOM.
402Please note the AST also should be parsed from stripped text.
403
404```js
405const SourceCode = require("eslint").SourceCode;
406
407const code = new SourceCode("\uFEFFvar foo = bar;", ast);
408
409assert(code.hasBOM === true);
410assert(code.text === "var foo = bar;");
411```
412
413### SourceCode#splitLines()
414
415This is a static function on `SourceCode` that is used to split the source code text into an array of lines.
416
417```js
418const SourceCode = require("eslint").SourceCode;
419
420const code = "var a = 1;\nvar b = 2;"
421
422// split code into an array
423const codeLines = SourceCode.splitLines(code);
424
425/*
426 Value of codeLines will be
427 [
428 "var a = 1;",
429 "var b = 2;"
430 ]
431 */
432```
433
56c4a2cb
DC
434---
435
eb39fafa
DC
436## Linter
437
438The `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.
439The `Linter` is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:
440
441* `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.
442
443For example:
444
445```js
446const Linter = require("eslint").Linter;
447const linter1 = new Linter({ cwd: 'path/to/project' });
448const linter2 = new Linter();
449```
450
451In this example, rules run on `linter1` will get `path/to/project` when calling `context.getCwd()`.
452Those 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).
453
454### Linter#verify
455
456The most important method on `Linter` is `verify()`, which initiates linting of the given text. This method accepts three arguments:
457
458* `code` - the source code to lint (a string or instance of `SourceCode`).
459* `config` - a configuration object that has been processed and normalized by CLIEngine using eslintrc files and/or other configuration arguments.
460 * **Note**: If you want to lint text and have your configuration be read and processed, use CLIEngine's [`executeOnFiles`](#cliengineexecuteonfiles) or [`executeOnText`](#cliengineexecuteontext) instead.
461* `options` - (optional) Additional options for this run.
462 * `filename` - (optional) the filename to associate with the source code.
463 * `preprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `preprocess` method.
464 * `postprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `postprocess` method.
465 * `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.
466 * `disableFixes` - (optional) when set to `true`, the linter doesn't make either the `fix` or `suggestions` property of the lint result.
467 * `allowInlineConfig` - (optional) set to `false` to disable inline comments from changing ESLint rules.
468 * `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.
469
470If the third argument is a string, it is interpreted as the `filename`.
471
472You can call `verify()` like this:
473
474```js
475const Linter = require("eslint").Linter;
476const linter = new Linter();
477
478const messages = linter.verify("var foo;", {
479 rules: {
480 semi: 2
481 }
482}, { filename: "foo.js" });
483
484// or using SourceCode
485
486const Linter = require("eslint").Linter,
487 linter = new Linter(),
488 SourceCode = require("eslint").SourceCode;
489
490const code = new SourceCode("var foo = bar;", ast);
491
492const messages = linter.verify(code, {
493 rules: {
494 semi: 2
495 }
496}, { filename: "foo.js" });
497```
498
499The `verify()` method returns an array of objects containing information about the linting warnings and errors. Here's an example:
500
501```js
502{
503 fatal: false,
504 ruleId: "semi",
505 severity: 2,
506 line: 1,
507 column: 23,
508 message: "Expected a semicolon.",
509 fix: {
510 range: [1, 15],
511 text: ";"
512 }
513}
514```
515
516The information available for each linting message is:
517
518* `column` - the column on which the error occurred.
519* `fatal` - usually omitted, but will be set to true if there's a parsing error (not related to a rule).
520* `line` - the line on which the error occurred.
521* `message` - the message that should be output.
522* `nodeType` - the node or token type that was reported with the problem.
523* `ruleId` - the ID of the rule that triggered the messages (or null if `fatal` is true).
524* `severity` - either 1 or 2, depending on your configuration.
525* `endColumn` - the end column of the range on which the error occurred (this property is omitted if it's not range).
526* `endLine` - the end line of the range on which the error occurred (this property is omitted if it's not range).
527* `fix` - an object describing the fix for the problem (this property is omitted if no fix is available).
528* `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)).
529
530Linting 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.
531
532You can also get an instance of the `SourceCode` object used inside of `linter` by using the `getSourceCode()` method:
533
534```js
535const Linter = require("eslint").Linter;
536const linter = new Linter();
537
538const messages = linter.verify("var foo = bar;", {
539 rules: {
540 semi: 2
541 }
542}, { filename: "foo.js" });
543
544const code = linter.getSourceCode();
545
546console.log(code.text); // "var foo = bar;"
547```
548
549In this way, you can retrieve the text and AST used for the last run of `linter.verify()`.
550
551### Linter#verifyAndFix()
552
553This 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.
554
555```js
556const Linter = require("eslint").Linter;
557const linter = new Linter();
558
559const messages = linter.verifyAndFix("var foo", {
560 rules: {
561 semi: 2
562 }
563});
564```
565
566Output object from this method:
567
568```js
569{
570 fixed: true,
571 output: "var foo;",
572 messages: []
573}
574```
575
576The information available is:
577
578* `fixed` - True, if the code was fixed.
579* `output` - Fixed code text (might be the same as input if no fixes were applied).
580* `messages` - Collection of all messages for the given code (It has the same information as explained above under `verify` block).
581
582### Linter#defineRule
583
584Each `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.
585
586```js
587const Linter = require("eslint").Linter;
588const linter = new Linter();
589
590linter.defineRule("my-custom-rule", {
591 // (an ESLint rule)
592
593 create(context) {
594 // ...
595 }
596});
597
598const results = linter.verify("// some source text", { rules: { "my-custom-rule": "error" } });
599```
600
601### Linter#defineRules
602
603This is a convenience method similar to `Linter#defineRule`, except that it allows you to define many rules at once using an object.
604
605```js
606const Linter = require("eslint").Linter;
607const linter = new Linter();
608
609linter.defineRules({
610 "my-custom-rule": { /* an ESLint rule */ create() {} },
611 "another-custom-rule": { /* an ESLint rule */ create() {} }
612});
613
614const results = linter.verify("// some source text", {
615 rules: {
616 "my-custom-rule": "error",
617 "another-custom-rule": "warn"
618 }
619});
620```
621
622### Linter#getRules
623
624This method returns a map of all loaded rules.
625
626```js
627const Linter = require("eslint").Linter;
628const linter = new Linter();
629
630linter.getRules();
631
632/*
633Map {
634 'accessor-pairs' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
635 'array-bracket-newline' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
636 ...
637}
638*/
639```
640
641### Linter#defineParser
642
643Each instance of `Linter` holds a map of custom parsers. If you want to define a parser programmatically, you can add this function
644with 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.
645
646```js
647const Linter = require("eslint").Linter;
648const linter = new Linter();
649
650linter.defineParser("my-custom-parser", {
651 parse(code, options) {
652 // ...
653 }
654});
655
656const results = linter.verify("// some source text", { parser: "my-custom-parser" });
657```
658
659### Linter#version/Linter.version
660
661Each instance of `Linter` has a `version` property containing the semantic version number of ESLint that the `Linter` instance is from.
662
663```js
664const Linter = require("eslint").Linter;
665const linter = new Linter();
666
667linter.version; // => '4.5.0'
668```
669
670There is also a `Linter.version` property that you can read without instantiating `Linter`:
671
672```js
673const Linter = require("eslint").Linter;
674
675Linter.version; // => '4.5.0'
676```
677
678## linter
679
680The `eslint.linter` object (deprecated) is an instance of the `Linter` class as defined [above](#linter). `eslint.linter` exists for backwards compatibility, but we do not recommend using it because any mutations to it are shared among every module that uses `eslint`. Instead, please create your own instance of `eslint.Linter`.
681
682```js
683const linter = require("eslint").linter;
684
685const messages = linter.verify("var foo;", {
686 rules: {
687 semi: 2
688 }
689}, { filename: "foo.js" });
690```
691
692Note: This API is deprecated as of 4.0.0.
693
56c4a2cb
DC
694---
695
eb39fafa
DC
696## CLIEngine
697
56c4a2cb
DC
698⚠️ The `CLIEngine` class has been deprecated in favor of the `ESLint` class as of v7.0.0.
699
eb39fafa
DC
700The primary Node.js API is `CLIEngine`, which is the underlying utility that runs the ESLint command line interface. This object will read the filesystem for configuration and file information but will not output any results. Instead, it allows you direct access to the important information so you can deal with the output yourself.
701
702You can get a reference to the `CLIEngine` by doing the following:
703
704```js
705const CLIEngine = require("eslint").CLIEngine;
706```
707
708The `CLIEngine` is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:
709
710* `allowInlineConfig` - Set to `false` to disable the use of configuration comments (such as `/*eslint-disable*/`). Corresponds to `--no-inline-config`.
711* `baseConfig` - Can optionally be set to a config object that has the same schema as `.eslintrc.*`. This will used as a default config, and will be merged with any configuration defined in `.eslintrc.*` files, with the `.eslintrc.*` files having precedence.
712* `cache` - Operate only on changed files (default: `false`). Corresponds to `--cache`.
713* `cacheFile` - Name of the file where the cache will be stored (default: `.eslintcache`). Corresponds to `--cache-file`. Deprecated: use `cacheLocation` instead.
714* `cacheLocation` - Name of the file or directory where the cache will be stored (default: `.eslintcache`). Corresponds to `--cache-location`.
715* `configFile` - The configuration file to use (default: null). If `useEslintrc` is true or not specified, this configuration will be merged with any configuration defined in `.eslintrc.*` files, with options in this configuration having precedence. Corresponds to `-c`.
716* `cwd` - Path to a directory that should be considered as the current working directory.
717* `envs` - An array of environments to load (default: empty array). Corresponds to `--env`. Note: This differs from `.eslintrc.*` / `baseConfig`, where instead the option is called `env` and is an object.
718* `errorOnUnmatchedPattern` - Set to `false` to prevent errors when pattern is unmatched. Corresponds to `--no-error-on-unmatched-pattern`.
719* `extensions` - An array of filename extensions that should be checked for code. The default is an array containing just `".js"`. Corresponds to `--ext`. It is only used in conjunction with directories, not with filenames, glob patterns or when using `executeOnText()`.
720* `fix` - A boolean or a function (default: `false`). If a function, it will be passed each linting message and should return a boolean indicating whether the fix should be included with the output report (errors and warnings will not be listed if fixed). Files on disk are never changed regardless of the value of `fix`. To persist changes to disk, call [`outputFixes()`](#cliengineoutputfixes).
721* `fixTypes` - An array of rule types for which fixes should be applied (default: `null`). This array acts like a filter, only allowing rules of the given types to apply fixes. Possible array values are `"problem"`, `"suggestion"`, and `"layout"`.
722* `globals` - An array of global variables to declare (default: empty array). Corresponds to `--global`, and similarly supports passing `'name:true'` to denote a writeable global. Note: This differs from `.eslintrc.*` / `baseConfig`, where `globals` is an object.
723* `ignore` - False disables use of `.eslintignore`, `ignorePath` and `ignorePattern` (default: true). Corresponds to `--no-ignore`.
724* `ignorePath` - The ignore file to use instead of `.eslintignore` (default: null). Corresponds to `--ignore-path`.
725* `ignorePattern` - Glob patterns for paths to ignore. String or array of strings.
726* `parser` - Specify the parser to be used (default: `espree`). Corresponds to `--parser`.
727* `parserOptions` - An object containing parser options (default: empty object). Corresponds to `--parser-options`.
728* `plugins` - An array of plugins to load (default: empty array). Corresponds to `--plugin`.
729* `reportUnusedDisableDirectives` - When set to `true`, adds reported errors for unused `eslint-disable` directives when no problems would be reported in the disabled area anyway (default: false). Corresponds to `--report-unused-disable-directives`.
730* `resolvePluginsRelativeTo` - Determines the folder where plugins should be resolved from. Should be used when an integration installs plugins and uses those plugins to lint code on behalf of the end user. Corresponds to `--resolve-plugins-relative-to`.
731* `rulePaths` - An array of directories to load custom rules from (default: empty array). Corresponds to `--rulesdir`.
732* `rules` - An object of rules to use (default: null). Corresponds to `--rule`.
733* `useEslintrc` - Set to false to disable use of `.eslintrc` files (default: true). Corresponds to `--no-eslintrc`.
734* `globInputPaths` - Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
735
736To programmatically set `.eslintrc.*` options not supported above (such as `extends`,
737`overrides` and `settings`), define them in a config object passed to `baseConfig` instead.
738
739For example:
740
741```js
742const CLIEngine = require("eslint").CLIEngine;
743
744const cli = new CLIEngine({
745 baseConfig: {
746 extends: ["eslint-config-shared"],
747 settings: {
748 sharedData: "Hello"
749 }
750 },
751 envs: ["browser", "mocha"],
752 useEslintrc: false,
753 rules: {
754 semi: 2
755 }
756});
757```
758
759In this example, a new `CLIEngine` instance is created that extends a configuration called
760`"eslint-config-shared"`, a setting named `"sharedData"` and two environments (`"browser"`
761and `"mocha"`) are defined, loading of `.eslintrc` and `package.json` files are disabled,
762and the `semi` rule enabled as an error. You can then call methods on `cli` and these options
763will be used to perform the correct action.
764
765Note: Currently `CLIEngine` does not validate options passed to it, but may start doing so in the future.
766
767### CLIEngine#executeOnFiles()
768
769If you want to lint one or more files, use the `executeOnFiles()` method. This method accepts a single argument, which is an array of files and/or directories to traverse for files. You can pass the same values as you would using the ESLint command line interface, such as `"."` to search all JavaScript files in the current directory. Here's an example:
770
771```js
772const CLIEngine = require("eslint").CLIEngine;
773
774const cli = new CLIEngine({
775 envs: ["browser", "mocha"],
776 useEslintrc: false,
777 rules: {
778 semi: 2
779 }
780});
781
782// lint myfile.js and all files in lib/
783const report = cli.executeOnFiles(["myfile.js", "lib/"]);
784```
785
786The return value is an object containing the results of the linting operation. Here's an example of a report object:
787
788```js
789{
790 results: [
791 {
792 filePath: "/Users/eslint/project/myfile.js",
793 messages: [{
794 ruleId: "semi",
795 severity: 2,
796 message: "Missing semicolon.",
797 line: 1,
798 column: 13,
799 nodeType: "ExpressionStatement",
800 fix: { range: [12, 12], text: ";" }
801 }, {
802 ruleId: "no-useless-escape",
803 severity: 1,
804 message: "disallow unnecessary escape characters",
805 line: 1,
806 column: 10,
807 nodeType: "ExpressionStatement",
808 suggestions: [{
809 desc: "Remove unnecessary escape. This maintains the current functionality.",
810 fix: { range: [9, 10], text: "" }
811 }, {
812 desc: "Escape backslash to include it in the RegExp.",
813 fix: { range: [9, 9], text: "\\" }
814 }]
815 }],
816 errorCount: 1,
817 warningCount: 1,
818 fixableErrorCount: 1,
819 fixableWarningCount: 0,
820 source: "\"use strict\"\n"
821 }
822 ],
823 errorCount: 1,
824 warningCount: 0,
825 fixableErrorCount: 1,
826 fixableWarningCount: 0,
827 usedDeprecatedRules: []
828}
829```
830
831You can also pass `fix: true` when instantiating the `CLIEngine` in order to have it figure out what fixes can be applied.
832
833```js
834const CLIEngine = require("eslint").CLIEngine;
835
836const cli = new CLIEngine({
837 envs: ["browser", "mocha"],
838 fix: true, // difference from last example
839 useEslintrc: false,
840 rules: {
841 semi: 2,
842 quotes: [2, "double"]
843 }
844});
845
846// lint myfile.js and all files in lib/
847const report = cli.executeOnFiles(["myfile.js", "lib/"]);
848```
849
850```js
851{
852 results: [
853 {
854 filePath: "/Users/eslint/project/myfile.js",
855 messages: [
856 {
857 ruleId: "semi",
858 severity: 2,
859 message: "Missing semicolon.",
860 line: 1,
861 column: 13,
862 nodeType: "ExpressionStatement",
863 fix: { range: [12, 12], text: ";" }
864 },
865 {
866 ruleId: "func-name-matching",
867 severity: 2,
868 message: "Function name `bar` should match variable name `foo`",
869 line: 2,
870 column: 5,
871 nodeType: "VariableDeclarator"
872 }
873 ],
874 errorCount: 2,
875 warningCount: 0,
876 fixableErrorCount: 1,
877 fixableWarningCount: 0,
878 output: "\"use strict\";\nvar foo = function bar() {};\nfoo();\n"
879 }
880 ],
881 errorCount: 2,
882 warningCount: 0,
883 fixableErrorCount: 1,
884 fixableWarningCount: 0,
885 usedDeprecatedRules: []
886}
887```
888
889If the operation ends with a parsing error, you will get a single message for this file, with `fatal: true` added as an extra property.
890
891```js
892{
893 results: [
894 {
895 filePath: "./myfile.js",
896 messages: [
897 {
898 ruleId: null,
899 fatal: true,
900 severity: 2,
901 message: "Parsing error: Unexpected token foo",
902 line: 1,
903 column: 10
904 }
905 ],
906 errorCount: 1,
907 warningCount: 0,
908 fixableErrorCount: 0,
909 fixableWarningCount: 0,
910 source: "function foo() {}"
911 }
912 ],
913 errorCount: 1,
914 warningCount: 0,
915 fixableErrorCount: 0,
916 fixableWarningCount: 0,
917 usedDeprecatedRules: []
918}
919```
920
921The top-level report object has a `results` array containing all linting results for files that had warnings or errors (any files that did not produce a warning or error are omitted). Each file result includes:
922
923* `filePath` - Path to the given file.
924* `messages` - Array containing the result of calling `linter.verify()` on the given file.
925* `errorCount` and `warningCount` - The exact number of errors and warnings respectively on the given file.
926* `source` - The source code for the given file. This property is omitted if this file has no errors/warnings or if the `output` property is present.
927* `output` - The source code for the given file with as many fixes applied as possible, so you can use that to rewrite the files if necessary. This property is omitted if no fix is available.
928
6f036462 929The top-level report object also has `errorCount` and `warningCount` which give the exact number of errors and warnings respectively on all the files. Additionally, `usedDeprecatedRules` signals any deprecated rules used and their replacement (if available). Specifically, it is an array of objects with properties like so:
eb39fafa
DC
930
931* `ruleId` - The name of the rule (e.g. `indent-legacy`).
932* `replacedBy` - An array of rules that replace the deprecated rule (e.g. `["indent"]`).
933
934Once you get a report object, it's up to you to determine how to output the results. Fixes will not be automatically applied to the files, even if you set `fix: true` when constructing the `CLIEngine` instance. To apply fixes to the files, call [`outputFixes`](#cliengineoutputfixes).
935
936### CLIEngine#resolveFileGlobPatterns()
937
938You can pass filesystem-style or glob patterns to ESLint and have it function properly. In order to achieve this, ESLint must resolve non-glob patterns into glob patterns before determining which files to execute on. The `resolveFileGlobPatterns()` methods uses the current settings from `CLIEngine` to resolve non-glob patterns into glob patterns. Pass an array of patterns that might be passed to the ESLint CLI and it will return an array of glob patterns that mean the same thing. Here's an example:
939
940```js
941const CLIEngine = require("eslint").CLIEngine;
942
943const cli = new CLIEngine({
944});
945
946// pass an array of patterns
947const globPatterns = cli.resolveFileGlobPatterns(["."]);
948console.log(globPatterns[i]); // ["**/*.js"]
949```
950
951### CLIEngine#getConfigForFile()
952
953If you want to retrieve a configuration object for a given file, use the `getConfigForFile()` method. This method accepts one argument, a file path, and returns an object represented the calculated configuration of the file. Here's an example:
954
955```js
956const CLIEngine = require("eslint").CLIEngine;
957
958const cli = new CLIEngine({
959 envs: ["browser", "mocha"],
960 useEslintrc: false,
961 rules: {
962 semi: 2
963 }
964});
965
966const config = cli.getConfigForFile("myfile.js");
967```
968
969Once you have the configuration information, you can pass it into the `linter` object:
970
971```js
972const CLIEngine = require("eslint").CLIEngine,
973 Linter = require("eslint").Linter;
974
975const linter = new Linter();
976const cli = new CLIEngine({
977 envs: ["browser", "mocha"],
978 useEslintrc: false,
979 rules: {
980 semi: 2
981 }
982});
983
984const config = cli.getConfigForFile("myfile.js");
985
986const messages = linter.verify('var foo;', config);
987```
988
989### CLIEngine#executeOnText()
990
991If you already have some text to lint, then you can use the `executeOnText()` method to lint that text. The linter will assume that the text is a file in the current working directory, and so will still obey any `.eslintrc` and `.eslintignore` files that may be present. Here's an example:
992
993```js
994const CLIEngine = require("eslint").CLIEngine;
995
996const cli = new CLIEngine({
997 envs: ["browser", "mocha"],
998 useEslintrc: false,
999 rules: {
1000 semi: 2
1001 }
1002});
1003
1004// Lint the supplied text and optionally set a filename that is displayed in the report
1005const report = cli.executeOnText("var foo = 'bar';", "foo.js");
1006
1007// In addition to the above, warn if the resolved file name is ignored.
1008const reportAndWarnOnIgnoredFile = cli.executeOnText("var foo = 'bar';", "foo.js", true);
1009```
1010
1011The `report` returned from `executeOnText()` is in the same format as from `executeOnFiles()`, but there is only ever one result in `report.results`.
1012
1013If a filename in the optional second parameter matches a file that is configured to be ignored, then this function returns no errors or warnings. The method includes an additional optional boolean third parameter. When `true`, a resolved file name that is ignored will return a warning.
1014
1015### CLIEngine#addPlugin()
1016
1017Loads a plugin from configuration object with specified name. Name can include plugin prefix ("eslint-plugin-")
1018
1019```js
1020const CLIEngine = require("eslint").CLIEngine;
1021const cli = new CLIEngine({
1022 ignore: true
1023});
1024cli.addPlugin("eslint-plugin-processor", {
1025 processors: {
1026 ".txt": {
1027 preprocess: function(text) {
1028 return [text];
1029 },
1030 postprocess: function(messages) {
1031 return messages[0];
1032 }
1033 }
1034 }
1035});
1036```
1037
1038### CLIEngine#isPathIgnored()
1039
1040Checks if a given path is ignored by ESLint.
1041
1042```js
1043const CLIEngine = require("eslint").CLIEngine;
1044
1045const cli = new CLIEngine({
1046 ignore: true,
1047 ignorePath: ".customIgnoreFile"
1048});
1049
1050const isIgnored = cli.isPathIgnored("foo/bar.js");
1051```
1052
1053### CLIEngine#getFormatter()
1054
1055Retrieves a formatter, which you can then use to format a report object. The argument is either the name of a built-in formatter:
1056
1057* "[checkstyle](../user-guide/formatters#checkstyle)"
1058* "[codeframe](../user-guide/formatters#codeframe)"
1059* "[compact](../user-guide/formatters#compact)"
1060* "[html](../user-guide/formatters#html)"
1061* "[jslint-xml](../user-guide/formatters#jslint-xml)"
1062* "[json](../user-guide/formatters#json)"
1063* "[junit](../user-guide/formatters#junit)"
1064* "[stylish](../user-guide/formatters#stylish)" (the default)
1065* "[table](../user-guide/formatters#table)"
1066* "[tap](../user-guide/formatters#tap)"
1067* "[unix](../user-guide/formatters#unix)"
1068* "[visualstudio](../user-guide/formatters#visualstudio)"
1069
1070or the full path to a JavaScript file containing a custom formatter. You can also omit the argument to retrieve the default formatter.
1071
1072```js
1073const CLIEngine = require("eslint").CLIEngine;
1074
1075const cli = new CLIEngine({
1076 envs: ["browser", "mocha"],
1077 useEslintrc: false,
1078 rules: {
1079 semi: 2
1080 }
1081});
1082
1083// lint myfile.js and all files in lib/
1084const report = cli.executeOnFiles(["myfile.js", "lib/"]);
1085
1086// get the default formatter
1087const formatter = cli.getFormatter();
1088
1089// Also could do...
1090// const formatter = cli.getFormatter("compact");
1091// const formatter = cli.getFormatter("./my/formatter.js");
1092
1093// output to console
1094console.log(formatter(report.results));
1095```
1096
1097**Note:** Also available as a static function on `CLIEngine`.
1098
1099```js
1100// get the default formatter by calling the static function
1101const formatter = CLIEngine.getFormatter();
1102```
1103
1104**Important:** You must pass in the `results` property of the report. Passing in `report` directly will result in an error.
1105
1106### CLIEngine#getErrorResults()
1107
1108This is a static function on `CLIEngine`. It can be used to filter out all the non error messages from the report object.
1109
1110```js
1111const CLIEngine = require("eslint").CLIEngine;
1112
1113const cli = new CLIEngine({
1114 envs: ["browser", "mocha"],
1115 useEslintrc: false,
1116 rules: {
1117 semi: 2
1118 }
1119});
1120
1121// lint myfile.js and all files in lib/
1122const report = cli.executeOnFiles(["myfile.js", "lib/"]);
1123
1124// only get the error messages
1125const errorReport = CLIEngine.getErrorResults(report.results)
1126```
1127
1128**Important:** You must pass in the `results` property of the report. Passing in `report` directly will result in an error.
1129
1130### CLIEngine#outputFixes()
1131
1132This is a static function on `CLIEngine` that is used to output fixes from `report` to disk. It does by looking for files that have an `output` property in their results. Here's an example:
1133
1134```js
1135const CLIEngine = require("eslint").CLIEngine;
1136
1137const cli = new CLIEngine({
1138 envs: ["browser", "mocha"],
1139 fix: true,
1140 useEslintrc: false,
1141 rules: {
1142 semi: 2
1143 }
1144});
1145
1146// lint myfile.js and all files in lib/
1147const report = cli.executeOnFiles(["myfile.js", "lib/"]);
1148
1149// output fixes to disk
1150CLIEngine.outputFixes(report);
1151```
1152
1153### CLIEngine#getRules()
1154
1155This method returns a map of all loaded rules. Under the hood, it calls [Linter#getRules](#lintergetrules).
1156
1157```js
1158const CLIEngine = require("eslint").CLIEngine;
1159const cli = new CLIEngine();
1160
1161cli.getRules();
1162
1163/*
1164Map {
1165 'accessor-pairs' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
1166 'array-bracket-newline' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
1167 ...
1168}
1169*/
1170```
1171
1172
1173### CLIEngine.version
1174
1175`CLIEngine` has a static `version` property containing the semantic version number of ESLint that it comes from.
1176
1177```js
1178require("eslint").CLIEngine.version; // '4.5.0'
1179```
1180
56c4a2cb
DC
1181---
1182
eb39fafa
DC
1183## RuleTester
1184
1185`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.
1186
1187Example usage:
1188
1189```js
1190"use strict";
1191
1192const rule = require("../../../lib/rules/my-rule"),
1193 RuleTester = require("eslint").RuleTester;
1194
1195const ruleTester = new RuleTester();
1196
1197ruleTester.run("my-rule", rule, {
1198 valid: [
1199 {
1200 code: "var foo = true",
1201 options: [{ allowFoo: true }]
1202 }
1203 ],
1204
1205 invalid: [
1206 {
1207 code: "var invalidVariable = true",
1208 errors: [{ message: "Unexpected invalid variable." }]
1209 },
1210 {
1211 code: "var invalidVariable = true",
1212 errors: [{ message: /^Unexpected.+variable/ }]
1213 }
1214 ]
1215});
1216```
1217
1218The `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:
1219
1220```js
1221const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } });
1222```
1223
1224The `RuleTester#run()` method is used to run the tests. It should be passed the following arguments:
1225
1226* The name of the rule (string)
1227* The rule object itself (see ["working with rules"](./working-with-rules))
1228* An object containing `valid` and `invalid` properties, each of which is an array containing test cases.
1229
1230A test case is an object with the following properties:
1231
1232* `code` (string, required): The source code that the rule should be run on
1233* `options` (array, optional): The options passed to the rule. The rule severity should not be included in this list.
1234* `filename` (string, optional): The filename for the given case (useful for rules that make assertions about filenames).
1235
1236In addition to the properties above, invalid test cases can also have the following properties:
1237
1238* `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):
1239 * `message` (string/regexp): The message for the error
1240 * `messageId` (string): The Id for the error. See [testing errors with messageId](#testing-errors-with-messageid) for details
1241 * `data` (object): Placeholder data which can be used in combination with `messageId`
1242 * `type` (string): The type of the reported AST node
1243 * `line` (number): The 1-based line number of the reported location
1244 * `column` (number): The 1-based column number of the reported location
1245 * `endLine` (number): The 1-based line number of the end of the reported location
1246 * `endColumn` (number): The 1-based column number of the end of the reported location
1247 * `suggestions` (array): An array of objects with suggestion details to check. See [Testing Suggestions](#testing-suggestions) for details
1248
1249 If a string is provided as an error instead of an object, the string is used to assert the `message` of the error.
1250* `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.
1251
1252Any 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:
1253
1254```js
1255{
1256 code: "let foo;",
1257 parserOptions: { ecmaVersion: 2015 }
1258}
1259```
1260
1261If 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.
1262
1263#### Testing errors with `messageId`
1264
1265If 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`.
1266
1267```js
1268{
1269 code: "let foo;",
1270 errors: [{ messageId: "unexpected" }]
1271}
1272```
1273
1274For messages with placeholders, a test case can also use `data` property to additionally assert reported error's `message`.
1275
1276```js
1277{
1278 code: "let foo;",
1279 errors: [{ messageId: "unexpected", data: { name: "foo" } }]
1280}
1281```
1282
1283Please 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`.
1284
1285#### Testing Suggestions
1286
1287Suggestions 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):
1288
1289* `desc` (string): The suggestion `desc` value
1290* `messageId` (string): The suggestion `messageId` value for suggestions that use `messageId`s
1291* `data` (object): Placeholder data which can be used in combination with `messageId`
1292* `output` (string): A code string representing the result of applying the suggestion fix to the input code
1293
1294Example:
1295
1296```js
1297ruleTester.run("my-rule-for-no-foo", rule, {
1298 valid: [],
1299 invalid: [{
1300 code: "var foo;",
1301 errors: [{
1302 suggestions: [{
1303 desc: "Rename identifier 'foo' to 'bar'",
1304 output: "var bar;"
1305 }]
1306 }]
1307 }]
1308})
1309```
1310
1311`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.
1312
1313```js
1314ruleTester.run("my-rule-for-no-foo", rule, {
1315 valid: [],
1316 invalid: [{
1317 code: "var foo;",
1318 errors: [{
1319 suggestions: [{
1320 messageId: "renameFoo",
1321 data: { newName: "bar" },
1322 output: "var bar;"
1323 }]
1324 }]
1325 }]
1326})
1327```
1328
1329### Customizing RuleTester
1330
1331`RuleTester` depends on two functions to run tests: `describe` and `it`. These functions can come from various places:
1332
13331. 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.
13341. Otherwise, if `describe` and `it` are present as globals, `RuleTester` will use `global.describe` and `global.it` to run tests. This allows `RuleTester` to work when using frameworks like [Mocha](https://mochajs.org/) without any additional configuration.
13351. 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`, without needing a testing framework.
1336
1337`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. (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.it` and `RuleTester.describe`.)
1338
1339Example of customizing `RuleTester`:
1340
1341```js
1342"use strict";
1343
1344const RuleTester = require("eslint").RuleTester,
1345 test = require("my-test-runner"),
1346 myRule = require("../../../lib/rules/my-rule");
1347
1348RuleTester.describe = function(text, method) {
1349 RuleTester.it.title = text;
1350 return method.call(this);
1351};
1352
1353RuleTester.it = function(text, method) {
1354 test(RuleTester.it.title + ": " + text, method);
1355};
1356
1357// then use RuleTester as documented
1358
1359const ruleTester = new RuleTester();
1360
1361ruleTester.run("my-rule", myRule, {
1362 valid: [
1363 // valid test cases
1364 ],
1365 invalid: [
1366 // invalid test cases
1367 ]
1368})
1369```
1370
56c4a2cb
DC
1371---
1372
eb39fafa
DC
1373## Deprecated APIs
1374
1375* `cli` - the `cli` object has been deprecated in favor of `CLIEngine`. As of v1.0.0, `cli` is no longer exported and should not be used by external tools.
1376* `linter` - the `linter` object has been deprecated in favor of `Linter` as of v4.0.0.
56c4a2cb
DC
1377* `CLIEngine` - the `CLIEngine` class has been deprecated in favor of the `ESLint` class as of v7.0.0.
1378
1379---
1380
ebb53d86 1381[configuration object]: ../user-guide/configuring
56c4a2cb
DC
1382[builtin-formatters]: https://eslint.org/docs/user-guide/formatters/
1383[thirdparty-formatters]: https://www.npmjs.com/search?q=eslintformatter
1384[eslint]: #eslint-class
1385[eslint-constructor]: #-new-eslintoptions
6f036462
TL
1386[eslint-lintfiles]: #-eslintlintfilespatterns
1387[eslint-linttext]: #-eslintlinttextcode-options
1388[eslint-calculateconfigforfile]: #-eslintcalculateconfigforfilefilepath
1389[eslint-ispathignored]: #-eslintispathignoredfilepath
1390[eslint-loadformatter]: #-eslintloadformatternameorpath
56c4a2cb 1391[eslint-version]: #-eslintversion
6f036462
TL
1392[eslint-outputfixes]: #-eslintoutputfixesresults
1393[eslint-geterrorresults]: #-eslintgeterrorresultsresults
56c4a2cb
DC
1394[lintresult]: #-lintresult-type
1395[lintmessage]: #-lintmessage-type
1396[editinfo]: #-editinfo-type
1397[formatter]: #-formatter-type
1398[linter]: #linter