Sub topic 11
Enforcing JSDoc with ESLint
Code review tends to miss JSDoc mistakes. Someone renames a parameter and forgets the @param line. Someone types @parm instead of @param. A new exported function ships with no comment at all. None of these break the program, so tests won't catch them. A linter will. This chapter shows how to use eslint-plugin-jsdoc to check your comments every time you run ESLint.
It assumes you know how to write JSDoc blocks, @param, @returns, and type expressions from earlier chapters. It also assumes you have run ESLint before, or at least know it is a tool that reads your source files and reports problems according to a set of rules.
What the plugin checks
eslint-plugin-jsdoc adds rules to ESLint, all named with a jsdoc/ prefix. ESLint parses your files and passes each JSDoc block to those rules, along with the code the block is attached to. Because a rule can see both the comment and the function signature, it can compare the two.
The rules fall into three groups:
- Presence rules decide whether a comment or tag has to exist.
jsdoc/require-jsdocrequires a block on certain functions.jsdoc/require-paramrequires a@paramfor each parameter. - Correctness rules check that what you wrote matches the code and the JSDoc grammar.
jsdoc/check-param-namescompares@paramnames with the real parameter names.jsdoc/valid-typesrejects type expressions that don't parse. - Style rules keep formatting consistent.
jsdoc/check-alignmentchecks that the asterisks line up, andjsdoc/tag-linescontrols blank lines between tags.
Installing and enabling the recommended rules
Install ESLint and the plugin as development dependencies:
npm install --save-dev eslint eslint-plugin-jsdocRecent ESLint versions use a "flat config" file named eslint.config.js. It exports an array of configuration objects, and ESLint merges them in order. The plugin ships ready-made flat configs. The quickest way to start is the recommended one:
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
jsdoc.configs['flat/recommended'],
];This file uses import and export, so Node has to treat it as an ES module. Either set "type": "module" in package.json or name the file eslint.config.mjs.
The flat/recommended config registers the plugin and turns on a sensible set of rules at the warn level. The plugin also offers other variants:
| Config name | What it does |
|---|---|
| `flat/recommended` | Recommended rules, reported as warnings |
| `flat/recommended-error` | The same rules, reported as errors |
| `flat/recommended-typescript` | For `.ts` files, where types live in the code; it discourages putting types in JSDoc |
| `flat/recommended-typescript-flavor` | For JavaScript files that use TypeScript-style JSDoc types |
For a plain JavaScript project that uses JSDoc types and checkJs, start with flat/recommended. Switch to flat/recommended-error once the codebase is clean, so new problems fail the build.
Seeing the rules fire
Create src/math.js with some typical mistakes in it:
/**
* Divides one number by another.
* @parm {number} a - The dividend.
* @param {number} divisor - The divisor.
*/
export function divide(dividend, divisor) {
return dividend / divisor;
}
/**
* @param {string|} value
* @returns {string}
*/
export function shout(value) {
return String(value).toUpperCase();
}
export function square(n) {
return n * n;
}Run ESLint on the folder:
npx eslint srcThe exact wording depends on the plugin version, but you will get warnings like these:
jsdoc/check-tag-namesreports that@parmis not a known tag.jsdoc/require-paramreports thatdividendhas no@param. The misspelled tag doesn't count.jsdoc/require-returnsreports thatdividereturns a value but has no@returns.jsdoc/valid-typesreports thatstring|is not a valid type expression.squaregets no warning, even though it has no comment. The next section explains why.
Each line of the report gives the position, the severity, the message, and the rule name. You need the rule name to configure or disable that rule.
Automatic fixes
Some rules can fix what they find. Run:
npx eslint src --fixAlignment and blank-line problems are rewritten for you. jsdoc/require-param inserts a stub @param line for each missing parameter. Read the fixed file afterwards. The stub has the right parameter name, but you still have to write the description and check the type. A stub with no description satisfies require-param while telling the reader nothing.
Requiring comments where they matter
jsdoc/require-jsdoc is in the recommended set, but by default it only looks at function declarations. That is why square above passed: it is an exported function declaration, but the default warning is easy to overlook, and arrow functions, class declarations, and methods are not checked at all.
Most teams want comments on the public API and don't care about small private helpers. The publicOnly option limits the rule to exported code. The require option lists the kinds of code that need a comment:
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
jsdoc.configs['flat/recommended'],
{
files: ['src/**/*.js'],
rules: {
'jsdoc/require-jsdoc': ['error', {
publicOnly: true,
require: {
FunctionDeclaration: true,
ArrowFunctionExpression: true,
ClassDeclaration: true,
MethodDefinition: true,
},
}],
'jsdoc/require-description': 'warn',
'jsdoc/check-param-names': 'error',
},
},
];The second object doesn't list the plugin under plugins. In flat config, a plugin registered in one object (here, by the recommended config) is available to rules in later objects. The later object overrides the severity of the rules it names and adds jsdoc/require-description, which is not in the recommended set. That rule fails any block that has tags but no description text.
With this config, export const area = (r) => Math.PI * r * r; now needs a comment, and a non-exported helper does not.
Useful rules and what they catch
The recommended set covers most needs. These are the rules you will run into most often:
| Rule | Catches | In recommended |
|---|---|---|
| `require-jsdoc` | Missing block on configured code | Yes |
| `require-param` | Parameter with no `@param` | Yes |
| `require-returns` | Function that returns a value with no `@returns` | Yes |
| `require-param-type` | `@param` with no `{type}` | Yes |
| `check-param-names` | `@param` names that don't match the signature, or are in the wrong order | Yes |
| `check-tag-names` | Unknown or misspelled tags | Yes |
| `check-types` | Types written in a form other than the preferred one | Yes |
| `valid-types` | Type expressions that don't parse | Yes |
| `no-undefined-types` | Types that refer to names that aren't defined | Yes |
| `require-description` | Blocks with no description text | No |
| `require-example` | Blocks with no `@example` | No |
require-example is usually too strict to apply everywhere. If you use it, limit it to a few public entry points with a files pattern.
Destructured and optional parameters
check-param-names understands destructuring. If a function takes { id, name }, the plugin expects a root @param plus nested names:
/**
* Formats a user label.
* @param {object} user - The user to format.
* @param {string} user.id - Unique identifier.
* @param {string} user.name - Display name.
* @returns {string} The label.
*/
export function label({ id, name }) {
return `${name} (${id})`;
}Without the user.id and user.name lines, require-param reports the missing nested properties. Optional parameters written as [taxRate=0.2] pass check-param-names as long as the name matches.
Plugin settings
Some behavior is controlled by shared settings rather than per-rule options. You put them under settings.jsdoc in a config object:
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
jsdoc.configs['flat/recommended'],
{
settings: {
jsdoc: {
mode: 'typescript',
tagNamePreference: {
return: 'returns',
arg: 'param',
},
},
},
},
];modechooses the type grammar thatvalid-typesand related rules accept.typescript(the default in current versions) accepts TypeScript-style syntax such asimport('./user.js').UserandArray<string>. That matches what// @ts-checkandcheckJsunderstand. Thejsdocandclosuremodes are stricter and reject some of that syntax.tagNamePreferencepicks one spelling for tags that have synonyms. With the mapping above,check-tag-namesflags@returnand@argand can rewrite them to@returnsand@param.
Suppressing a rule locally
Sometimes a rule is wrong for one spot, such as a generated file or a deliberately undocumented internal export. Disable it for that line only and say why:
// eslint-disable-next-line jsdoc/require-jsdoc -- internal, re-exported for tests only
export function _resetCache() {}The text after -- is a reason that ESLint ignores but reviewers can read. To exclude generated files completely, add a config object with ignores: ['src/generated/**']. Don't scatter disable comments through those files.
ESLint and TypeScript checking together
eslint-plugin-jsdoc and TypeScript's checkJs overlap a little, but they do different jobs.
| Question | Tool that answers it |
|---|---|
| Does every exported function have a comment? | ESLint (`require-jsdoc`) |
| Do `@param` names match the signature? | ESLint (`check-param-names`) |
| Is `@parm` a typo? | ESLint (`check-tag-names`) |
| Is the caller passing a `number` where `{string}` is declared? | TypeScript (`checkJs`) |
| Does the function body return what `@returns` claims? | TypeScript (`checkJs`) |
ESLint checks the comments as documentation. TypeScript checks the code against the types in those comments. A project that uses both gets complete, well-formed comments with types that are enforced. Run both in continuous integration:
{
"scripts": {
"lint": "eslint src --max-warnings 0",
"typecheck": "tsc",
"check": "npm run lint && npm run typecheck"
}
}--max-warnings 0 makes ESLint exit with an error code if there are any warnings. Without it, a config that reports everything as warn would never fail the build.
Common mistakes
- Forgetting module mode. If
eslint.config.jsusesimportbutpackage.jsonhas no"type": "module", Node fails to load the config. Rename it to.mjsor set the type. - Assuming recommended means complete. By default
require-jsdocignores arrow functions, classes, and methods. Configurerequireexplicitly. - Warnings that never fail. The recommended rules are warnings. Use
flat/recommended-erroror--max-warnings 0in CI. - Mode mismatch. If you write
import()types forcheckJsbut setmode: 'jsdoc',valid-typesreports valid TypeScript syntax as errors. Keepmode: 'typescript'. - Accepting fix stubs as documentation. Autofixed
@paramlines have no descriptions. Turn onrequire-param-description(it is in the recommended set) so those stubs get flagged until someone fills them in.
Exercise
A function export const toCents = (amount) => Math.round(amount * 100); has no JSDoc comment, yet npx eslint src with only jsdoc.configs['flat/recommended'] reports nothing for it. Why, and what change makes ESLint require a comment on it?
Show answer
By default jsdoc/require-jsdoc only checks function declarations, and toCents is an arrow function assigned to a const. Add a config object that sets 'jsdoc/require-jsdoc': ['error', { publicOnly: true, require: { ArrowFunctionExpression: true, FunctionDeclaration: true } }]. Because the function is exported, publicOnly still includes it.
Exercise
You rename a parameter from items to list but leave @param {string[]} items - Values to join. in the comment. Which rule reports this, and can eslint --fix make the comment fully correct?
Show answer
jsdoc/check-param-names reports that the documented name doesn't match the signature, and jsdoc/require-param may also report that list is undocumented. A fix can at most add a stub @param list line. It cannot move the description or judge whether the description is still accurate, so you must edit the comment yourself.
Exercise
Your project uses /** @typedef {import('./user.js').User} User */ and checkJs. After you add settings: { jsdoc: { mode: 'closure' } }, ESLint starts reporting the typedef as an invalid type. What is going on, and what is the fix?
Show answer
In closure mode the plugin parses types with the Closure Compiler grammar, which has no import() type expressions, so jsdoc/valid-types rejects it. Set mode to 'typescript' (or remove the setting, since typescript is the default) so the plugin accepts the same syntax TypeScript's checkJs understands.
Exercise
Your CI runs eslint src and passes, but the report shows 40 jsdoc warnings. Give two ways to make CI fail on these problems.
Show answer
Run ESLint with --max-warnings 0 so any warning gives a non-zero exit code, or switch from jsdoc.configs['flat/recommended'] to jsdoc.configs['flat/recommended-error'] (or raise individual rules to 'error') so the problems are reported as errors.