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