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