### JSDoc with File Overview Rule
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates the use of the `jsdoc/require-file-overview` rule in conjunction with code examples. It shows a simple example with a comment indicating its purpose.
```js
/**
* Does quux
* @example
* // Do it!
* quux();
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"plugins":["jsdoc"],"rules":{"jsdoc/require-file-overview":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}]
```
--------------------------------
### Arbitrary Example Content in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Shows how to include arbitrary content as an example in JSDoc. This is useful when the example is not strictly code but descriptive text or comments.
```js
/**
* @example
* // arbitrary example content
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false}]
```
--------------------------------
### Check Examples for Required Captions
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This configuration enforces that all `@example` tags must include a caption, flagging examples that lack one.
```typescript
/**
* @example
Valid usage
* quux(); // does something useful
*
* @example
* quux('random unwanted arg'); // results in an error
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}]
// Message: Caption is expected for examples.
```
--------------------------------
### Check Examples with Matching File Name and Missing Semicolon
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example uses `matchingFileName` to apply rules based on a specific file context and flags missing semicolons in `@example` tags.
```typescript
/**
* @example const idx = 5;
* quux2()
*/
function quux2 () {
}
// "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"dummy.js"}]
// Message: @example error (semi): Missing semicolon.
```
```typescript
/**
* @example const idx = 5;
*
* quux2()
*/
function quux2 () {
}
// "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"dummy.js"}]
// Message: @example error (semi): Missing semicolon.
```
--------------------------------
### Example Code Regex Configuration
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Configure regex to whitelist or blacklist examples for linting. Use `exampleCodeRegex` to specify patterns that should be linted, and `rejectExampleCodeRegex` for patterns that should be excluded. If neither is provided, all examples are matched.
```json
{
"rules": {
"jsdoc/check-examples": [
"error",
{
"exampleCodeRegex": "^```(?:js|javascript)([\\s\\S]*)```$",
"rejectExampleCodeRegex": "^`$"
}
]
}
}
```
--------------------------------
### JSDoc Example with Inline Config
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example shows a JSDoc comment with an example that includes an inline ESLint configuration. `allowInlineConfig: true` enables the processing of such configurations.
```js
/**
* @example
* test() // eslint-disable-line semi
*/
function quux () {}
// "jsdoc/check-examples": ["error"|"warn", {"allowInlineConfig":true,"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"noDefaultExampleRules":true}]
```
--------------------------------
### Executable Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates a JSDoc comment with an executable code snippet. The `noDefaultExampleRules` option can be set to `false` to allow default ESLint rules to be applied to the example code.
```js
/**
* @example
* quux(); // does something useful
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-undef":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}]
```
--------------------------------
### Install ESLint
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/README.md
Install ESLint locally or globally. This is a prerequisite for using eslint-plugin-jsdoc.
```sh
npm install --save-dev eslint
```
--------------------------------
### Passing example: JSDoc for class method
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block for a class method, where the rule is configured to check block starts.
```typescript
class MyClass {
/**
* Description.
*/
method() {}
}
```
--------------------------------
### JSDoc with decorator example (alternative formatting)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-indentation.md
Similar to the previous example, but with slightly different code block formatting.
```typescript
/**
* @example ```
* @MyDecorator({
* myOptions: 42
* })
* export class MyClass {}
* ```
*/
function MyDecorator(options: { myOptions: number }) {
return (Base: Function) => {};
}
```
--------------------------------
### JSDoc with decorator example
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-indentation.md
Demonstrates a JSDoc example with a TypeScript decorator.
```typescript
/**
* @example
* ```
* @MyDecorator({
* myOptions: 42
* })
* export class MyClass {}
* ```
*/
function MyDecorator(options: { myOptions: number }) {
return (Base: Function) => {};
}
```
--------------------------------
### Check Examples for ID Length Rule (Default)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates the default behavior of flagging short identifiers like 'm' when they appear in `@example` tags, without specific regex or file matching.
```typescript
/**
* @example const m = 5;
* quux2();
*/
function quux2 () {
}
// Message: @example warning (id-length): Identifier name 'm' is too short (< 2).
```
--------------------------------
### Install ESLint and JSDoc Plugin
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Install ESLint and the JSDoc plugin as development dependencies using npm.
```bash
npm install --save-dev eslint eslint-plugin-jsdoc
```
--------------------------------
### JSDoc with example and returns tag
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-indentation.md
Combines an example code block with a returns tag.
```javascript
/**
* foo
*
* @example
* anArray.filter((a) => {
* return a.b;
* });
* @returns
* eeee
*/
function quux () {
}
```
--------------------------------
### Passing JSDoc Examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-example.md
These examples demonstrate valid JSDoc comments that satisfy the 'jsdoc/require-example' rule. They include functions with properly formatted @example tags, constructors, and class members.
```typescript
/**
*
*/
/**
* @example
* // arbitrary example content
*/
function quux () {
}
```
```typescript
/**
* @example
* quux(); // does something useful
*/
function quux () {
}
```
```typescript
/**
* @example Valid usage
* quux(); // does something useful
*
* @example Invalid usage
* quux('random unwanted arg'); // results in an error
*/
function quux () {
}
```
```typescript
/**
* @constructor
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}]
```
```typescript
/**
* @constructor
* @example
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}]
```
```typescript
class Foo {
/**
*
*/
constructor () {
}
}
// "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}]
```
```typescript
/**
* @inheritdoc
*/
function quux () {
}
```
```typescript
/**
* @type {MyCallback}
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"exemptedBy":["type"]}]
```
```typescript
/**
* @example Some example code
*/
class quux {
}
// "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}]
```
```typescript
/**
*
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}]
```
```typescript
class TestClass {
/**
*
*/
get Test() { }
}
```
```typescript
class TestClass {
/**
* @example
*/
get Test() { }
}
```
```typescript
class TestClass {
/**
* @example Test
*/
get Test() { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}]
```
```typescript
class TestClass {
/**
*
*/
set Test(value) { }
}
```
```typescript
class TestClass {
/**
* @example
*/
set Test(value) { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkSetters":false}]
```
```typescript
class TestClass {
/**
* @example Test
*/
set Test(value) { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}]
```
```typescript
/**
*
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"exemptNoArguments":true}]
```
--------------------------------
### Flat Config Example
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/README.md
Import and configure eslint-plugin-jsdoc within a flat ESLint configuration. This example shows how to include recommended rules and customize specific rules.
```javascript
import jsdoc from 'eslint-plugin-jsdoc';
const config = [
// configuration included in plugin
jsdoc.configs['flat/recommended'],
// other configuration objects...
{
files: ['**/*.js'],
// `plugins` here is not necessary if including the above config
plugins: {
jsdoc,
},
rules: {
'jsdoc/require-description': 'warn'
}
}
];
export default config;
```
--------------------------------
### JSDoc with multiple examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/sort-tags.md
This example shows a JSDoc comment with multiple @example tags. It is used to test the configuration for handling multiple examples within a single JSDoc block.
```javascript
/**
* @param b
* @param a
* @returns {string}
* @example abc
*
*
* @example def
*/
function quux () {}
```
--------------------------------
### JSDoc with captioned example and JS code
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-indentation.md
An example with a caption and a JavaScript code block.
```javascript
/**
* @example
* Here is a long
* summary of this
* example
*
* ```js
* function hi () {
* alert('Hello');
* }
* ```
*/
```
--------------------------------
### JSDoc Example with Function Signature
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example shows a JSDoc comment with a detailed `@example` tag that includes a function signature and a call. It also includes parameter and return type descriptions.
```js
/**
* Test function.
*
* @example functionName (paramOne: string, paramTwo?: any,
* paramThree?: any): boolean test();
*
* @param {string} paramOne Parameter description.
* @param {any} [paramTwo] Parameter description.
* @param {any} [paramThree] Parameter description.
* @returns {boolean} Return description.
*/
const functionName = function (paramOne, paramTwo,
paramThree) {
return false;
};
```
--------------------------------
### Check Examples for Indentation Rule
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates the `jsdoc/check-examples` rule enforcing indentation within `@example` tags, flagging incorrect spacing.
```typescript
/**
* @example quux();
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}]
// Message: @example error (indent): Expected indentation of 0 spaces but found 1.
```
--------------------------------
### Enable ESLint to Lint @example Tags
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Configure the JSDoc processor plugin to lint JavaScript code within @example tags. Set options for checking examples, defaults, parameters, properties, caption requirements, and indentation.
```javascript
// eslint.config.js
import { getJsdocProcessorPlugin } from 'eslint-plugin-jsdoc';
export default [
// Configure the processor
{
files: ['**/*.js'],
plugins: {
examples: getJsdocProcessorPlugin({
checkExamples: true,
checkDefaults: false,
checkParams: false,
checkProperties: false,
captionRequired: false,
paddedIndent: 0,
}),
},
processor: 'examples/examples',
},
// Configure rules for @example content
{
files: ['**/*.md/*.js'],
rules: {
'no-undef': 'off',
'no-unused-vars': 'off',
'no-console': 'off',
},
},
];
```
--------------------------------
### Callback Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Shows a JSDoc example involving a callback function. This configuration uses `noDefaultExampleRules: false` to apply default ESLint rules to the example code.
```js
/**
* @example
* foo(function (err) {
* throw err;
* });
*/
function quux () {}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}]
```
--------------------------------
### JS Example with Regex in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Demonstrates using a regular expression to capture JavaScript code examples within JSDoc. This allows for more flexible parsing of example code blocks.
```js
/**
* @example ```js
alert('hello');
```
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"exampleCodeRegex":"/```js([\s\S]*)```/"}]
```
--------------------------------
### Install ESLint Plugin JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/README.md
Install the JSDoc plugin locally or globally, depending on your ESLint installation.
```sh
npm install --save-dev eslint-plugin-jsdoc
```
--------------------------------
### JSDoc with single line spacing for examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/sort-tags.md
This example configures the jsdoc/sort-tags rule to allow only one line of spacing between @example tags, ensuring examples are clearly separated but not overly spaced.
```javascript
/**
* @param b
* @param a
* @returns {string}
* @example abc
* @example def
*/
function quux () {}
```
--------------------------------
### Object Literal Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This snippet illustrates how to document an object literal with a JSDoc example. It uses `exampleCodeRegex` to specify the format of the example code, similar to function examples.
```js
/**
* @example ```js
alert('hello')
```
*/
var quux = {
};
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```js([\s\S]*)```"}]
```
--------------------------------
### JS Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This snippet shows a basic JavaScript example within a JSDoc comment. The `exampleCodeRegex` option can be used to specify the format of the example code.
```js
/**
* @example ```js
alert('hello');
```
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"exampleCodeRegex":"```js([\s\S]*)```"}]
```
--------------------------------
### Configure Padded Indent for @example
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Use the `paddedIndent` integer option to add fixed whitespace to the beginning of subsequent lines in `@example` blocks. This helps avoid linting issues with decorative whitespace by stripping it before evaluation. Only applied to `@example` linting.
```javascript
/**
* @example
* anArray.filter((a) => {
* return a.b;
* });
*/
```
--------------------------------
### Check Examples for No Alert Rule
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates how the `jsdoc/check-examples` rule, when configured with `no-alert`, flags the use of `alert()` within `@example` tags.
```typescript
/**
* @example alert('hello')
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-alert":2,"semi":["error","always"]}},"checkEslintrc":false}]
// Message: @example error (no-alert): Unexpected alert.
```
```typescript
/**
* @example alert('hello')
*/
class quux {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-alert":2,"semi":["error","always"]}},"checkEslintrc":false}]
// Message: @example error (no-alert): Unexpected alert.
```
--------------------------------
### Check Examples for Undefined Variables with No Default Rules
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
When `noDefaultExampleRules` is true, this example shows how the rule flags usage of undefined variables within `@example` tags, such as `quux()`.
```typescript
/**
* @example
* quux(); // does something useful
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-undef":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":true}]
// Message: @example error (no-undef): 'quux' is not defined.
```
--------------------------------
### Reject Function Type - Passing Example 2
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/reject-function-type.md
This example demonstrates the recommended approach of defining a callback type with its inputs and outputs, then referencing it.
```typescript
// Then reference the callback name as the type.
/**
* @param {FOOBAR} fooBar
*/
function quux (fooBar) {
console.log(fooBar(3));
}
```
--------------------------------
### Import Tag Examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/no-undefined-types.md
Various examples of the @import tag for importing types and modules.
```javascript
/**
* @import BadImportIgnoredByThisRule
*/
```
```javascript
/**
* @import LinterDef, { Sth as Something, Another as Another2 } from "eslint"
*/
```
```javascript
/**
* @import LinterDef2, * as LinterDef3 from "eslint"
*/
```
```javascript
/**
* @import { Linter } from "eslint"
*/
```
```javascript
/**
* @import LinterDefault from "eslint"
*/
```
```javascript
/**
* @import {Linter as Lintee} from "eslint"
*/
```
```javascript
/**
* @import * as Linters from "eslint"
*/
```
--------------------------------
### Passing example: JSDoc for constructor parameter
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block for a constructor parameter, demonstrating correct placement.
```typescript
class SomeClass {
constructor(
/**
* Description.
*/
param
) {};
method(
/**
* Description.
*/
param
) {};
}
```
--------------------------------
### jsdoc/require-returns Rule Examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-returns.md
Examples demonstrating the usage and configuration of the 'jsdoc/require-returns' rule, which enforces the presence of return tags in JSDoc comments.
```APIDOC
## jsdoc/require-returns Rule Examples
### Description
This rule enforces that JSDoc comments include a `@returns` tag when a function is expected to return a value.
### Method
N/A (Configuration Rule)
### Endpoint
N/A
### Parameters
#### Query Parameters
- **`contexts`** (array) - Optional - Specifies the contexts in which the rule should be applied. Can be a string or an object with `context` and `forceRequireReturn` properties.
- **`publicOnly`** (boolean) - Optional - If true, the rule only applies to public functions.
### Request Example
```json
{
"rules": {
"jsdoc/require-returns": [
"error",
{
"contexts": [
"FunctionDeclaration",
{
"context": "TSEmptyBodyFunctionExpression",
"forceRequireReturn": true
}
]
}
]
}
}
```
### Response
N/A (This is a linter rule configuration, not an API endpoint.)
### Error Handling
N/A
```
--------------------------------
### Missing JSDoc @example Description
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-example.md
This snippet shows a function with an @example tag but no description, which is flagged by the 'jsdoc/require-example' rule. Ensure the @example tag includes descriptive content.
```typescript
/**
* @example
*/
function quux () {
}
// Message: Missing JSDoc @example description.
```
```typescript
/**
* @constructor
* @example
*/
function quux () {
}
// Message: Missing JSDoc @example description.
```
```typescript
class TestClass {
/**
* @example
*/
get Test() { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}]
// Message: Missing JSDoc @example description.
```
```typescript
class TestClass {
/**
* @example
*/
set Test(value) { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}]
// Message: Missing JSDoc @example description.
```
--------------------------------
### Example JSDoc with Code
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/tag-lines.md
A JSDoc comment block containing an example code snippet.
```javascript
/**
* My Test Function, with some example code.
*
* ```js
* new Foo();
* ```
*
*
* @param {string} bar
*/
function myTestFunction(bar) {
}
```
--------------------------------
### Configure TypeScript Processor for @example Tags
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Configure the JSDoc processor plugin to work with TypeScript files and @example tags containing TypeScript code. Specify the parser, matching file name pattern, and example code regex.
```javascript
// eslint.config.js
import { getJsdocProcessorPlugin } from 'eslint-plugin-jsdoc';
import ts, { parser as typescriptEslintParser } from 'typescript-eslint';
export default [
{
files: ['**/*.ts'],
languageOptions: {
parser: typescriptEslintParser,
},
plugins: {
examples: getJsdocProcessorPlugin({
parser: typescriptEslintParser,
matchingFileName: 'dummy.md/*.ts',
exampleCodeRegex: '^```ts([\s\S]*)```\s*$',
}),
},
processor: 'examples/examples',
},
...ts.configs.recommended,
{
files: ['**/*.md/*.ts'],
languageOptions: {
parser: typescriptEslintParser,
},
rules: {
'no-extra-semi': 'error',
...ts.configs.disableTypeChecked.rules,
},
},
];
```
--------------------------------
### Passing example: JSDoc for array element
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block for an element within an array, where the rule is configured to check block starts.
```typescript
const values = [
/**
* Description.
*/
value,
];
```
--------------------------------
### Available Preset Configurations
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Example of how to use different preset configurations provided by eslint-plugin-jsdoc for various project types and TypeScript support levels.
```javascript
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
// Standard JavaScript with JSDoc
// jsdoc.configs['flat/recommended'],
// jsdoc.configs['flat/recommended-error'],
// TypeScript syntax files
// jsdoc.configs['flat/recommended-typescript'],
// jsdoc.configs['flat/recommended-typescript-error'],
// JavaScript files with TypeScript-flavored JSDoc
// jsdoc.configs['flat/recommended-typescript-flavor'],
// jsdoc.configs['flat/recommended-typescript-flavor-error'],
// TSDoc compatibility (for TypeDoc)
// jsdoc.configs['flat/recommended-tsdoc'],
// jsdoc.configs['flat/recommended-tsdoc-error'],
// Mixed JS/TS projects with automatic config selection
jsdoc.configs['flat/recommended-mixed'],
];
```
--------------------------------
### Inline {@tutorial} tag without content
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/valid-types.md
Shows an error for an inline {@tutorial} tag that is missing content.
```javascript
/**
* An inline {@tutorial} tag without content.
*/
```
--------------------------------
### Passing example: JSDoc for function variable
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block for a function's local variable, where the rule is configured to check block starts.
```typescript
function myFunction() {
/**
* Description.
*/
let value;
}
```
--------------------------------
### Passing example: JSDoc within object literal
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block within an object literal, where the rule is configured to check block starts.
```typescript
{
/**
* Description.
*/
let value;
}
```
--------------------------------
### TypeScript Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example demonstrates a JSDoc comment with a TypeScript code snippet. The `baseConfig` is configured with `@typescript-eslint/parser` to handle TypeScript syntax.
```js
/**
* @example
* const list: number[] = [1, 2, 3];
* quux(list);
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parser":"@typescript-eslint/parser","parserOptions":{"ecmaVersion":6},"rules":{"semi":["error","always"]}},"checkEslintrc":false}]
```
--------------------------------
### Customizing require-file-overview with Additional Tags
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-file-overview.md
This example shows how to configure the require-file-overview rule to enforce specific requirements for the '@license' tag. It mandates that each file must have exactly one '@license' tag, but does not restrict its placement to the beginning of the file.
```js
{
"license": {
"mustExist": true,
"preventDuplicates": true,
}
}
```
--------------------------------
### Valid @yields tag with description on new line (Passing Example)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-yields-description.md
This example shows an alternative valid format where the description for the `@yields` tag starts on a new line, which is also accepted by the `require-yields-description` rule.
```typescript
/**
* @yields
* The results.
*/
export function *test1(): IterableIterator { yield "hello"; }
```
--------------------------------
### Inline Example in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
Illustrates an inline code example within a JSDoc comment. This configuration also uses `noDefaultExampleRules: false` to enable default rule checking.
```js
/**
* @example quux();
*/
function quux () {}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}]
```
--------------------------------
### Incomplete Example Snippet
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This snippet represents an incomplete example within the documentation, likely intended for further demonstration.
```typescript
/**
* @example const idx = 5;
```
--------------------------------
### Check Examples with Newline in Code Block Regex
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example uses `exampleCodeRegex` to match JavaScript code blocks that start with a newline, enforcing the `semi: "never"` rule and flagging extra semicolons.
```typescript
/**
* @example ```
* js alert('hello'); ```
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```\njs ([\s\S]*)```"}]
// Message: @example error (semi): Extra semicolon.
```
--------------------------------
### Valid @returns description (Passing Example)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-returns-description.md
This example shows a correctly formatted JSDoc comment with a @returns tag that includes a description.
```typescript
/**
* @returns Foo.
*/
function quux () {
}
```
--------------------------------
### Build Project with pnpm
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/CONTRIBUTING.md
Run this command after installing dependencies to update the 'dist' files, which include the main entry point 'dist/index.cjs'.
```shell
pnpm build
```
--------------------------------
### JSDoc Sentence Capitalization Error
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-description-complete-sentence.md
This example demonstrates a JSDoc comment where a sentence does not start with an uppercase character, violating the 'jsdoc/require-description-complete-sentence' rule.
```typescript
/**
* foo.
*/
function quux () {
}
```
```typescript
/**
* foo?
*/
function quux () {
}
```
```typescript
/**
* @description foo.
*/
function quux () {
}
```
```typescript
/**
* Foo.
*
* foo.
*/
function quux () {
}
```
```typescript
/**
* ัะตัั.
*/
function quux () {
}
```
```typescript
/**
* Foo.
*
* @param foo foo.
*/
function quux (foo) {
}
```
```typescript
/**
* Foo.
*
* @param foo bar
*/
function quux (foo) {
}
```
```typescript
/**
* Foo.
*
* @returns {number} foo
*/
function quux (foo) {
}
```
```typescript
/**
* Foo.
*
* @returns foo.
*/
function quux (foo) {
}
```
```typescript
/**
* lorem ipsum dolor sit amet, consectetur adipiscing elit.
* iaculis eu dignissim sed, ultrices sed nisi. nulla at ligula auctor, consectetur neque sed,
* tincidunt nibh. vivamus sit amet vulputate ligula. vivamus interdum elementum nisl,
* vitae rutrum tortor semper ut. morbi porta ante vitae dictum fermentum.
* proin ut nulla at quam convallis gravida in id elit. sed dolor mauris, blandit quis ante at,
* consequat auctor magna. duis pharetra purus in porttitor mollis.
*/
function longDescription (foo) {
}
```
```typescript
/**
* @return {number} bar
*/
function quux (foo) {
}
```
--------------------------------
### JSDoc with example code block
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-indentation.md
Includes an example code block within the JSDoc comment.
```javascript
/**
* foo
*
* @example
* anArray.filter((a) => {
* return a.b;
* });
*/
function quux () {
}
```
--------------------------------
### Failing example: Multiple asterisks at the beginning of middle lines
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/no-multi-asterisks.md
This JSDoc block starts with multiple asterisks, violating the rule for middle lines.
```ts
/**
**
*
*/
// Message: Should be no multiple asterisks on middle lines.
```
--------------------------------
### JSDoc with enum examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/sort-tags.md
This example demonstrates how to document enums using JSDoc, including inline examples of generating enum values. It covers different enum types like numeric, string, and mixed.
```javascript
/**
* @example
* enum Color { Red, Green, Blue }
* faker.helpers.enumValue(Color) // 1 (Green)
*
* enum Direction { North = 'North', South = 'South'}
* faker.helpers.enumValue(Direction) // 'South'
*
* enum HttpStatus { Ok = 200, Created = 201, BadRequest = 400, Unauthorized = 401 }
* faker.helpers.enumValue(HttpStatus) // 200 (Ok)
*
* @since 8.0.0
*/
```
--------------------------------
### JSDoc @param with disallowed name pattern
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/match-name.md
This example shows a JSDoc comment where parameters are expected to not start with 'arg'. It's useful for enforcing naming conventions.
```javascript
/**
* @param opt_a
* @param opt_b
*/
// "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg/i"}]}]
```
--------------------------------
### Enforce Start Lines After Block Description (No Tags)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/tag-lines.md
Enforces a specific number of lines after the block description when no tags are present. This example requires exactly one line.
```javascript
"jsdoc/tag-lines": ["error"|"warn", "any",{"startLinesWithNoTags":1}]
```
--------------------------------
### Check Examples with Matching File Name and ID Length Rule
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This example uses `matchingFileName` to apply rules based on a specific file context and flags short identifiers like 'j' based on the `id-length` rule.
```typescript
/**
* @example const j = 5;
* quux2();
*/
function quux2 () {
}
// "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"../../jsdocUtils.js"}]
// Message: @example warning (id-length): Identifier name 'j' is too short (< 2).
```
--------------------------------
### JSDoc Parameter Example (Permissive Mode)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/valid-types.md
An example of documenting an array parameter with a tuple type in permissive JSDoc mode.
```javascript
/**
* Foo function.
*
* @param {[number, string]} bar - The bar array.
*/
function foo(bar) {}
```
--------------------------------
### Enforce Start Lines After Block Description in JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/tag-lines.md
Enforces a specific number of lines after the block description before any tags appear. This example shows enforcing exactly one line.
```javascript
"jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}]
```
--------------------------------
### Interface Property with Start and End Lines Zero
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/tag-lines.md
This example shows an interface property 'checkbox' with JSDoc. The 'jsdoc/tag-lines' rule is configured with both 'endLines' and 'startLines' set to 0, disallowing any empty lines before or after the tag.
```typescript
export interface SubOptionTypeMap {
/**
* Checkboxes have two states - true (checked) and false (unchecked)
*
*/
checkbox: boolean
}
```
```typescript
// "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":0,"startLines":0}]
```
--------------------------------
### Configure match-description with custom matchDescription
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/match-description.md
Provide a custom regular expression to override the default `matchDescription` for JSDoc blocks and tags. This example enforces descriptions starting with a capital letter followed by any characters and ending with a period.
```javascript
{
'jsdoc/match-description': ['error', {matchDescription: '[A-Z].*\\.'}]
}
```
--------------------------------
### Failing examples for imports-as-dependencies
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/imports-as-dependencies.md
These examples demonstrate JSDoc import() statements that point to packages not found in project dependencies, triggering the rule.
```typescript
/**
* @type {null|import('sth').SomeApi}
*/
```
```typescript
/**
* @type {null|import('sth').SomeApi}
*/
// Settings: {"jsdoc":{"mode":"permissive"}}
```
```typescript
/**
* @type {null|import('missingpackage/subpackage').SomeApi}
*/
```
```typescript
/**
* @type {null|import('@sth/pkg').SomeApi}
*/
```
```typescript
/**
* @type {null|import('sinon').SomeApi}
*/
```
--------------------------------
### Check Examples for Missing Semicolon with Allow Inline Config False
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This configuration, with `allowInlineConfig: false` and `baseConfig` enforcing semicolons, flags missing semicolons in `@example` tags.
```typescript
/**
* @example
test() // eslint-disable-line semi
*/
function quux () {}
// "jsdoc/check-examples": ["error"|"warn", {"allowInlineConfig":false,"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"noDefaultExampleRules":true}]
// Message: @example error (semi): Missing semicolon.
```
--------------------------------
### Example Functions
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-returns.md
Illustrative JavaScript functions demonstrating different JSDoc comment styles and function structures.
```APIDOC
## Example Functions
### Description
These examples showcase various function definitions and JSDoc comment patterns, useful for understanding how eslint-plugin-jsdoc might parse and validate them.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
### Error Handling
N/A
```javascript
/**
* Description.
*/
async function foo() {
return new Promise(resolve => resolve());
}
/**
* @param ms time in millis
*/
export const sleep = (ms: number) =>
new Promise((res) => setTimeout(res, ms));
/**
* @param ms time in millis
*/
export const sleep = (ms: number) => {
return new Promise((res) => setTimeout(res, ms));
};
/**
* Reads a test fixture.
*
* @returns The file contents as buffer.
*/
export function readFixture(path: string): Promise;
/**
* Reads a test fixture.
*
* @returns {void}.
*/
export function readFixture(path: string): void;
/**
* Reads a test fixture.
*/
export function readFixture(path: string): void;
/**
* Reads a test fixture.
*/
export function readFixture(path: string);
/**
* Abstract method definition.
* @returns {string} The test value
*/
abstract class Test {
abstract Test(): string;
}
```
```
--------------------------------
### Enforce Caption Requirement for JSDoc Examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This configuration requires all JSDoc examples to have a caption. It's useful for ensuring examples are clearly labeled.
```javascript
// "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}]
```
--------------------------------
### Class Constructor with JSDoc
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-param.md
Demonstrates JSDoc for a class constructor and inheritance.
```APIDOC
## Class Constructor with JSDoc
### Description
This example illustrates JSDoc annotations for a base class constructor and how `@inheritDoc` can be used in a derived class.
### Base Class
```typescript
/** @abstract */
class base {
/** @param {boolean} arg0 */
constructor(arg0) {}
}
```
### Derived Class
```typescript
class foo extends base {
/** @inheritDoc */
constructor(arg0) {
super(arg0);
this.arg0 = arg0;
}
}
```
### Settings Example
```json
// Settings: {"jsdoc":{"mode":"closure"}}
```
```
--------------------------------
### Passing example: JSDoc with comment before
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example shows a valid JSDoc block preceded by a regular comment and an empty line, which is considered valid.
```typescript
/* Some comment */
/**
*
*/
```
--------------------------------
### Passing example: JSDoc with 2 lines before
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/lines-before-block.md
This example demonstrates a valid JSDoc block preceded by two empty lines, satisfying a configuration that requires two lines.
```typescript
// Some comment
/**
*
*/
```
--------------------------------
### JSDoc @parameter Tag Example with Configuration
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-tag-names.md
Demonstrates the '@parameter' tag with a configuration that specifies its structure and requirements.
```javascript
/**
* @parameter foo
*/
function quux (foo) {
}
// Settings: {"jsdoc":{"structuredTags":{"parameter":{"name":"namepath-referencing","required":["type","name"],"type":true}}}}
```
--------------------------------
### Missing @return description with alias (Failing Example)
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-returns-description.md
This example shows a failing case where the @return tag (an alias for @returns) is used without a description.
```typescript
/**
* @return
*/
function quux (foo) {
}
// Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}}
```
--------------------------------
### Check Examples for Unused Disable Directives
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
With `reportUnusedDisableDirectives: true`, this example shows how the rule flags unused `eslint-disable` comments within `@example` tags.
```typescript
/**
* @example test() // eslint-disable-line semi
*/
function quux () {}
// "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false,"noDefaultExampleRules":true,"reportUnusedDisableDirectives":true}]
// Message: @example error: Unused eslint-disable directive (no problems were reported from 'semi').
```
--------------------------------
### Function with JSDoc and Min Lines Setting
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-jsdoc.md
This example shows a function with JSDoc, configured with `maxLines: 3` and `minLines: 2`. The JSDoc meets the minimum line requirement.
```javascript
/**
* @func myFunction
*/
function myFunction() {
}
// Settings: {"jsdoc":{"maxLines":3,"minLines":2}}
```
--------------------------------
### Failing example: Multiple asterisks on middle lines with configuration
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/no-multi-asterisks.md
This failing example shows multiple asterisks on a middle line, specifically when `preventAtMiddleLines` is set to `true`.
```ts
/**
*
**
*/
// "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtMiddleLines":true}]
// Message: Should be no multiple asterisks on middle lines.
```
--------------------------------
### JSDoc Example Block Escaping
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/text-escaping.md
These examples show JSDoc @example blocks with code content that is correctly escaped for HTML or Markdown, preventing 'jsdoc/text-escaping' rule violations.
```javascript
/**
* @example
* ```
* Some things to escape: and > and ઼ and `test`
* ```
*/
// "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}]
```
```javascript
/**
* @example
* ```
* Some things to escape: and > and ઼ and `test`
* ```
*/
// "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}]
```
--------------------------------
### Generate Documentation with pnpm
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/CONTRIBUTING.md
Run this command after modifying files in the '.README' directory to integrate documentation changes into the main README.md file.
```shell
pnpm create-docs
```
--------------------------------
### JSDoc with Aligned Parameters and Multi-word Descriptions
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-line-alignment.md
Demonstrates JSDoc parameter alignment with multi-word descriptions.
```javascript
/**
* Function description
* description with post delimiter.
*
* @param {string} lorem Description.
* @param {int} sit Description multi words.
*/
const fn = ( lorem, sit ) => {}
```
--------------------------------
### JSDoc Example with Captions
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This configuration requires captions for JSDoc examples using the `captionRequired: true` option. It shows both valid and invalid usage examples with descriptive captions.
```js
/**
* @example Valid usage
* quux(); // does something useful
*
* @example Invalid usage
* quux('random unwanted arg'); // results in an error
*/
function quux () {
}
// "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}]
```
--------------------------------
### Configure require-returns Rule
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Configure the require-returns rule to mandate @returns documentation for functions with return statements. Options are available for async functions and constructors.
```javascript
// eslint.config.js
export default [
{
rules: {
'jsdoc/require-returns': [
'error',
{
checkConstructors: false,
checkGetters: true,
forceRequireReturn: false,
forceReturnsWithAsync: true,
exemptedBy: ['inheritdoc', 'type'],
},
],
},
},
];
```
--------------------------------
### Use Built-in JSDoc Example and Default Expression Configs
Source: https://context7.com/gajus/eslint-plugin-jsdoc/llms.txt
Apply built-in ESLint configurations for processing @example tags or default expression content. These configurations can be used individually or combined.
```javascript
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
// Process @example tags
...jsdoc.configs.examples,
// Or process @default, @param defaults, @property defaults
// ...jsdoc.configs['default-expressions'],
// Or process both
// ...jsdoc.configs['examples-and-default-expressions'],
];
```
--------------------------------
### Run Tests with Coverage
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/CONTRIBUTING.md
Use this command to run tests and view detailed coverage information. Coverage should be maintained at 100%.
```shell
pnpm test-cov
```
--------------------------------
### Missing JSDoc @example Declaration
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/require-example.md
This snippet demonstrates a function missing a JSDoc @example declaration, which violates the 'jsdoc/require-example' rule. Ensure JSDoc comments include an @example tag for functions.
```typescript
/**
*
*/
function quux () {
}
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
function quux (someParam) {
}
// "jsdoc/require-example": ["error"|"warn", {"exemptNoArguments":true}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
function quux () {
}
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
* @constructor
*/
function quux () {
}
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
class quux {
}
// "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
// "jsdoc/require-example": ["error"|"warn", {"contexts":["any"]}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
function quux () {
}
// "jsdoc/require-example": ["error"|"warn", {"exemptedBy":["notPresent"]}]
// Message: Missing JSDoc @example declaration.
```
```typescript
class TestClass {
/**
*
*/
get Test() { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}]
// Message: Missing JSDoc @example declaration.
```
```typescript
class TestClass {
/**
*
*/
set Test(value) { }
}
// "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
function quux (someParam) {
}
// "jsdoc/require-example": ["error"|"warn", {"enableFixer":true}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
*
*/
function quux (someParam) {
}
// "jsdoc/require-example": ["error"|"warn", {"enableFixer":false}]
// Message: Missing JSDoc @example declaration.
```
```typescript
/**
* Returns a Promise...
*
* @param {number} ms - The number of ...
*/
const sleep = (ms: number): Promise => {};
// "jsdoc/require-example": ["error"|"warn", {"contexts":["any"]}]
// Message: Missing JSDoc @example declaration.
```
--------------------------------
### JSDoc Array of Objects Parameter Example
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/valid-types.md
Shows how to document an array of objects, where each object has specific properties with their own types and descriptions.
```javascript
/**
* Assign the project to a list of employees.
* @param {Object[]} employees - The employees who are responsible for the project.
* @param {string} employees[].name - The name of an employee.
* @param {string} employees[].department - The employee's department.
*/
```
--------------------------------
### Check for Reserved Keywords in JSDoc Examples
Source: https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/check-examples.md
This configuration checks JSDoc examples for the use of reserved keywords like 'const', which can cause parsing errors. Ensure your examples are valid JavaScript.
```javascript
// "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false,"matchingFileName":"dummy.js"}]
```