From df809fdedc5fc92df4be8340e28baedbde605b4f Mon Sep 17 00:00:00 2001 From: Ben Perlmutter <57849986+bpmutter@users.noreply.github.com> Date: Tue, 21 Feb 2023 16:51:06 -0500 Subject: [PATCH] docs: Custom Formatters page cleanup/expansion (#16886) * docs: custom formatters cleanup/expansion * custom formatters page edits * Apply suggestions from code review * Apply suggestions from code review Co-authored-by: Nicholas C. Zakas Co-authored-by: Milos Djermanovic * implement NZ/MD feedback * Update docs/src/extend/custom-formatters.md * Update docs/src/extend/custom-formatters.md Co-authored-by: Nitin Kumar --------- Co-authored-by: Nicholas C. Zakas Co-authored-by: Milos Djermanovic Co-authored-by: Nitin Kumar --- docs/src/extend/custom-formatters.md | 274 ++++++++++++++------------- 1 file changed, 142 insertions(+), 132 deletions(-) diff --git a/docs/src/extend/custom-formatters.md b/docs/src/extend/custom-formatters.md index 4506f0f35fd..dc8024433bf 100644 --- a/docs/src/extend/custom-formatters.md +++ b/docs/src/extend/custom-formatters.md @@ -8,9 +8,15 @@ eleventyNavigation: --- -While ESLint has some built-in formatters available to format the linting results, it's also possible to create and distribute your own custom formatters. You can include custom formatters in your project directly or create an npm package to distribute them separately. +Custom formatters let you display linting results in a format that best fits your needs, whether that's in a specific file format, a certain display style, or a format optimized for a particular tool. -Each formatter is just a function that receives a `results` object and a `context` and returns a string. For example, the following is how the `json` built-in formatter is implemented: +ESLint also has [built-in formatters](../use/formatters/) that you can use. + +You can include custom formatters in your project directly or create an npm package to distribute them separately. + +## Creating a Custom Formatter + +Each formatter is a function that receives a `results` object and a `context` as arguments and returns a string. For example, the following is how the built-in [JSON formatter](../use/formatters/#json) is implemented: ```js //my-awesome-formatter.js @@ -29,37 +35,17 @@ module.exports = async function(results) { }; ``` -To run ESLint with this formatter, you can use the `-f` (or `--format`) command line flag: +To run ESLint with this formatter, you can use the [`-f` (or `--format`)](../use/command-line-interface#-f---format) command line flag. You must begin the path to a locally defined custom formatter with a period (`.`), such as `./my-awesome-formatter.js` or `../formatters/my-awesome-formatter.js`. ```bash eslint -f ./my-awesome-formatter.js src/ ``` -In order to use a local file as a custom formatter, you must begin the filename with a dot (such as `./my-awesome-formatter.js` or `../formatters/my-awesome-formatter.js`). - -## Packaging the Custom Formatter - -Custom formatters can also be distributed through npm packages. To do so, create an npm package with a name in the format of `eslint-formatter-*`, where `*` is the name of your formatter (such as `eslint-formatter-awesome`). Projects should then install the package and can use the custom formatter with the `-f` (or `--format`) flag like this: - -```bash -eslint -f awesome src/ -``` - -Because ESLint knows to look for packages beginning with `eslint-formatter-` when the specified formatter doesn't begin with a dot, there is no need to type `eslint-formatter-` when using a packaged custom formatter. - -Tips for `package.json`: - -* The `main` entry should be the JavaScript file implementing your custom formatter. -* Add these `keywords` to help users find your formatter: - * `"eslint"` - * `"eslint-formatter"` - * `"eslintformatter"` +The remainder of this section contains reference information on how to work with custom formatter functions. -See all [formatters on npm](https://www.npmjs.com/search?q=eslint-formatter); +### The `results` Argument -## The `results` Argument - -The `results` object passed into a formatter is an array of objects containing the lint results for individual files. Here's some example output: +The `results` object passed into a formatter is an array of [`result`](#the-result-object) objects containing the linting results for individual files. Here's an example output: ```js [ @@ -101,7 +87,7 @@ The `results` object passed into a formatter is an array of objects containing t ] ``` -### The `result` Object +#### The `result` Object @@ -109,13 +95,13 @@ also be manually applied to that page. --> Each object in the `results` array is a `result` object. Each `result` object contains the path of the file that was linted and information about linting issues that were encountered. Here are the properties available on each `result` object: * **filePath**: The absolute path to the file that was linted. -* **messages**: An array of `message` objects. See below for more info about messages. +* **messages**: An array of [`message`](#the-message-object) objects. See below for more info about messages. * **errorCount**: The number of errors for the given file. * **warningCount**: The number of warnings for the given file. * **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. * **output**: The source code for the given file with as many fixes applied as possible. This property is omitted if no fix is available. -### The `message` Object +##### The `message` Object Each `message` object contains information about the ESLint rule that was triggered by some source code. The properties available on each `message` object are: @@ -126,15 +112,17 @@ Each `message` object contains information about the ESLint rule that was trigge * **column**: the column where the issue is located. * **nodeType**: the type of the node in the [AST](https://github.com/estree/estree/blob/master/spec.md#node-objects) -## The `context` Argument +### The `context` Argument -The formatter function receives an object as the second argument. The object has the following properties: +The formatter function receives a `context` object as its second argument. The object has the following properties: -* `cwd` ... The current working directory. This value comes from the `cwd` constructor option of the [ESLint](../integrate/nodejs-api#-new-eslintoptions) class. -* `maxWarningsExceeded` (optional): If `--max-warnings` was set and the number of warnings exceeded the limit, this property's value will be an object containing two properties: `maxWarnings`, the value of the `--max-warnings` option, and `foundWarnings`, the number of lint warnings. -* `rulesMeta` ... The `meta` property values of rules. See the [Custom Rules](custom-rules) page for more information about rules. +* `cwd`: The current working directory. This value comes from the `cwd` constructor option of the [ESLint](../integrate/nodejs-api#-new-eslintoptions) class. +* `maxWarningsExceeded` (optional): If `--max-warnings` was set and the number of warnings exceeded the limit, this property's value is an object containing two properties: + * `maxWarnings`: the value of the `--max-warnings` option + * `foundWarnings`: the number of lint warnings +* `rulesMeta`: The `meta` property values of rules. See the [Custom Rules](custom-rules) page for more information about rules. -For example, here's what the object would look like if one rule, `no-extra-semi`, had been run: +For example, here's what the object would look like if the rule `no-extra-semi` had been run: ```js { @@ -161,67 +149,29 @@ For example, here's what the object would look like if one rule, `no-extra-semi` } ``` -**Note:** if a linting is executed by deprecated `CLIEngine` class, the `context` argument may be a different value because it is up to the API users. Please check whether the `context` argument is an expected value or not if you want to support legacy environments. - -## Examples - -### Summary formatter - -A formatter that only cares about the total count of errors and warnings will look like this: - -```javascript -module.exports = function(results, context) { - // accumulate the errors and warnings - var summary = results.reduce( - function(seq, current) { - seq.errors += current.errorCount; - seq.warnings += current.warningCount; - return seq; - }, - { errors: 0, warnings: 0 } - ); - - if (summary.errors > 0 || summary.warnings > 0) { - return ( - "Errors: " + - summary.errors + - ", Warnings: " + - summary.warnings + - "\n" - ); - } - - return ""; -}; -``` +**Note:** if a linting is executed by the deprecated `CLIEngine` class, the `context` argument may be a different value because it is up to the API users. Please check whether the `context` argument is an expected value or not if you want to support legacy environments. -Running `eslint` with the previous custom formatter, +### Passing Arguments to Formatters -```bash -eslint -f ./my-awesome-formatter.js src/ -``` +While formatter functions do not receive arguments in addition to the results object and the context, it is possible to pass additional data into custom formatters using the methods described below. -Will produce the following output: +#### Using Environment Variables -```bash -Errors: 2, Warnings: 4 -``` +Custom formatters have access to environment variables and so can change their behavior based on environment variable data. -### Detailed formatter +Here's an example that uses a `FORMATTER_SKIP_WARNINGS` environment variable to determine whether to show warnings in the results: -A more complex report will look something like this: +```js +module.exports = function(results) { + var skipWarnings = process.env.FORMATTER_SKIP_WARNINGS === "true"; -```javascript -module.exports = function(results, context) { var results = results || []; - var summary = results.reduce( function(seq, current) { current.messages.forEach(function(msg) { var logMessage = { filePath: current.filePath, ruleId: msg.ruleId, - ruleUrl: context.rulesMeta[msg.ruleId].docs.url, message: msg.message, line: msg.line, column: msg.column @@ -245,14 +195,16 @@ module.exports = function(results, context) { ); if (summary.errors.length > 0 || summary.warnings.length > 0) { + var warnings = !skipWarnings ? summary.warnings : []; // skip the warnings in that case + var lines = summary.errors - .concat(summary.warnings) + .concat(warnings) .map(function(msg) { return ( "\n" + msg.type + " " + - msg.ruleId + (msg.ruleUrl ? " (" + msg.ruleUrl + ")" : "") + + msg.ruleId + "\n " + msg.filePath + ":" + @@ -268,48 +220,119 @@ module.exports = function(results, context) { }; ``` -So running `eslint` with this custom formatter: +You would run ESLint with this custom formatter and an environment variable set like this: ```bash -eslint -f ./my-awesome-formatter.js src/ +FORMATTER_SKIP_WARNINGS=true eslint -f ./my-awesome-formatter.js src/ ``` -The output will be +The output would be: ```bash -error space-infix-ops (https://eslint.org/docs/rules/space-infix-ops) +error space-infix-ops src/configs/bundler.js:6:8 -error semi (https://eslint.org/docs/rules/semi) + +error semi src/configs/bundler.js:6:10 -warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) - src/configs/bundler.js:5:6 -warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) - src/configs/bundler.js:6:6 -warning no-shadow (https://eslint.org/docs/rules/no-shadow) - src/configs/bundler.js:65:32 -warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) - src/configs/clean.js:3:6 ``` -## Passing Arguments to Formatters +#### Complex Argument Passing -While formatter functions do not receive arguments in addition to the results object and the context, it is possible to pass additional data into custom formatters using the methods described below. +If you find the custom formatter pattern doesn't provide enough options for the way you'd like to format ESLint results, the best option is to use ESLint's built-in [JSON formatter](../use/formatters/#json) and pipe the output to a second program. For example: + +```bash +eslint -f json src/ | your-program-that-reads-JSON --option +``` -## Using Environment Variables +In this example, the `your-program-that-reads-json` program can accept the raw JSON of ESLint results and process it before outputting its own format of the results. You can pass as many command line arguments to that program as are necessary to customize the output. -Custom formatters have access to environment variables and so can change their behavior based on environment variable data. Here's an example that uses a `AF_SKIP_WARNINGS` environment variable to determine whether or not to show warnings in the results: +### Formatting for Terminals -```js -module.exports = function(results) { - var skipWarnings = process.env.AF_SKIP_WARNINGS === "true"; //af stands for awesome-formatter +Modern terminals like [iTerm2](https://www.iterm2.com/) or [Guake](http://guake-project.org/) expect a specific results format to automatically open filenames when they are clicked. Most terminals support this format for that purpose: + +```bash +file:line:column +``` + +## Packaging a Custom Formatter +Custom formatters can be distributed through npm packages. To do so, create an npm package with a name in the format `eslint-formatter-*`, where `*` is the name of your formatter (such as `eslint-formatter-awesome`). Projects should then install the package and use the custom formatter with the [`-f` (or `--format`)](../use/command-line-interface#-f---format) flag like this: + +```bash +eslint -f awesome src/ +``` + +Because ESLint knows to look for packages beginning with `eslint-formatter-` when the specified formatter doesn't begin with a period, you do not need to type `eslint-formatter-` when using a packaged custom formatter. + +Tips for the `package.json` of a custom formatter: + +* The [`main`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#main) entry point must be the JavaScript file implementing your custom formatter. +* Add these [`keywords`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#keywords) to help users find your formatter: + * `"eslint"` + * `"eslint-formatter"` + * `"eslintformatter"` + +See all [custom formatters on npm](https://www.npmjs.com/search?q=eslint-formatter). + +## Examples + +### Summary Formatter + +A formatter that only reports on the total count of errors and warnings will look like this: + +```javascript +module.exports = function(results, context) { + // accumulate the errors and warnings + var summary = results.reduce( + function(seq, current) { + seq.errors += current.errorCount; + seq.warnings += current.warningCount; + return seq; + }, + { errors: 0, warnings: 0 } + ); + + if (summary.errors > 0 || summary.warnings > 0) { + return ( + "Errors: " + + summary.errors + + ", Warnings: " + + summary.warnings + + "\n" + ); + } + + return ""; +}; +``` + +Run `eslint` with the above summary formatter: + +```bash +eslint -f ./my-awesome-formatter.js src/ +``` + +Will produce the following output: + +```bash +Errors: 2, Warnings: 4 +``` + +### Detailed Formatter + +A more complex report could look like this: + +```javascript +module.exports = function(results, context) { var results = results || []; + var summary = results.reduce( function(seq, current) { current.messages.forEach(function(msg) { var logMessage = { filePath: current.filePath, ruleId: msg.ruleId, + ruleUrl: context.rulesMeta[msg.ruleId].docs.url, message: msg.message, line: msg.line, column: msg.column @@ -333,16 +356,14 @@ module.exports = function(results) { ); if (summary.errors.length > 0 || summary.warnings.length > 0) { - var warnings = !skipWarnings ? summary.warnings : []; // skip the warnings in that case - var lines = summary.errors - .concat(warnings) + .concat(summary.warnings) .map(function(msg) { return ( "\n" + msg.type + " " + - msg.ruleId + + msg.ruleId + (msg.ruleUrl ? " (" + msg.ruleUrl + ")" : "") + "\n " + msg.filePath + ":" + @@ -358,36 +379,25 @@ module.exports = function(results) { }; ``` -You would run ESLint with this custom formatter and an environment variable set like this: +When you run ESLint with this custom formatter: ```bash -AF_SKIP_WARNINGS=true eslint -f ./my-awesome-formatter.js src/ +eslint -f ./my-awesome-formatter.js src/ ``` -The output would be: +The output is: ```bash -error space-infix-ops +error space-infix-ops (https://eslint.org/docs/rules/space-infix-ops) src/configs/bundler.js:6:8 - -error semi +error semi (https://eslint.org/docs/rules/semi) src/configs/bundler.js:6:10 -``` - -### Complex Argument Passing - -If you find the custom formatter pattern doesn't provide enough options for the way you'd like to format ESLint results, the best option is to use ESLint's built-in [JSON formatter](../use/formatters/) and pipe the output to a second program. For example: - -```bash -eslint -f json src/ | your-program-that-reads-JSON --option -``` - -In this example, the `your-program-that-reads-json` program can accept the raw JSON of ESLint results and process it before outputting its own format of the results. You can pass as many command line arguments to that program as are necessary to customize the output. - -## Note: Formatting for Terminals - -Modern terminals like [iTerm2](https://www.iterm2.com/) or [Guake](http://guake-project.org/) expect a specific results format to automatically open filenames when they are clicked. Most terminals support this format for that purpose: - -```bash -file:line:column +warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) + src/configs/bundler.js:5:6 +warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) + src/configs/bundler.js:6:6 +warning no-shadow (https://eslint.org/docs/rules/no-shadow) + src/configs/bundler.js:65:32 +warning no-unused-vars (https://eslint.org/docs/rules/no-unused-vars) + src/configs/clean.js:3:6 ```