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