Sub topic 10
Generating a Documentation Site with jsdoc
The comments you have written so far already help readers of the source code and anyone using an editor with IntelliSense. The jsdoc command-line tool turns those same comments into a browsable HTML website, with one page per class and module, a navigation sidebar, and links between related symbols. This chapter covers installing and running the tool, controlling it with a configuration file, organizing output with @module, changing templates, and fixing the errors people usually run into.
This chapter assumes you can run commands with npm and npx, that you know ES module import/export, and that you have read the earlier chapters on comment syntax, @param/@returns, and documenting classes and modules.
How jsdoc Builds a Site
The jsdoc tool reads your JavaScript files and parses every /** ... */ comment. For each documented symbol it builds a doclet, a plain data object that records the symbol's name, kind (function, class, member, typedef), description, parameters, and other tags. Once all files are parsed, it hands the complete set of doclets to a template, which is the code that writes the HTML.
There are two practical consequences. A symbol with no JSDoc comment produces no doclet, so it does not appear on the site. Also, the template only knows what the doclets contain. When a page looks wrong, the cause is usually a tag that produced a different doclet than you expected, and the template is rarely at fault.
Installing and Running jsdoc
Install jsdoc as a development dependency so every contributor gets the same version:
npm install --save-dev jsdoc
npx jsdoc src -r -d docsThe second command processes the src directory. -r (recurse) tells it to descend into subdirectories, and -d docs writes the output to docs. Open docs/index.html in a browser to see the result.
Without -r, jsdoc reads only the files directly inside src. This causes the most common surprise: a project with code in src/models/ and src/utils/ gets a nearly empty site.
The options you will use most often:
| Option | Meaning |
|---|---|
| `-r`, `--recurse` | Scan subdirectories of the given paths |
| `-d <dir>`, `--destination <dir>` | Output directory (default `./out`) |
| `-c <file>`, `--configure <file>` | Path to a configuration file |
| `-R <file>`, `--readme <file>` | Markdown file to use as the home page |
| `-t <dir>`, `--template <dir>` | Template directory to render with |
| `-p`, `--private` | Include symbols marked `@private` |
| `-X`, `--explain` | Print doclets as JSON instead of writing HTML |
| `--pedantic` | Treat warnings as errors |
Add a script to package.json so nobody has to remember the flags:
{
"scripts": {
"docs": "jsdoc -c jsdoc.json"
},
"devDependencies": {
"jsdoc": "^4.0.0"
}
}Then npm run docs builds the site.
The Configuration File
Command-line flags are fine for quick experiments. A configuration file keeps the settings in version control and allows options that have no flag. jsdoc accepts a JSON file or a CommonJS .js file that exports an object. Pass it with -c:
{
"source": {
"include": ["src"],
"includePattern": "\\.(js|mjs)$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins": ["plugins/markdown"],
"opts": {
"destination": "docs",
"recurse": true,
"readme": "README.md"
},
"templates": {
"cleverLinks": true,
"default": {
"outputSourceFiles": true
}
}
}Save this as jsdoc.json in the project root. Here is what each section does.
source
include lists the files and directories to process. includePattern is a regular expression that file names must match. The default matches .js, .jsdoc, and .jsx, so .mjs files are skipped unless you widen the pattern as shown. excludePattern removes matching paths. The example skips any file or folder whose name starts with an underscore. Because this is a regular expression inside a JSON string, every backslash must be doubled.
You can also list exact paths under exclude, for example "exclude": ["src/vendor"].
opts
Anything under opts mirrors a command-line option: destination is -d, recurse is -r, readme is -R, template is -t, and private is -p. If you pass a flag on the command line as well, the flag wins.
plugins
Plugins hook into parsing and can change comments or doclets. plugins/markdown ships with jsdoc and converts Markdown in descriptions and tags such as @param, @returns, and @example captions into HTML. With it, backticks, bold text, and lists in your descriptions render properly.
templates
cleverLinks: true renders {@link} targets that are URLs in normal text and links to symbols in monospace. Setting outputSourceFiles to false stops the default template from publishing pretty-printed copies of your source code. Turn this off when the documentation is public and the source is not.
What Ends Up on the Site
The default template creates these files in the output directory:
| File | Contents |
|---|---|
| `index.html` | The README, rendered as the home page |
| `module-<name>.html` | One page per `@module` |
| `<ClassName>.html` | One page per documented class |
| `global.html` | Every documented symbol not inside a module, class, or namespace |
| `<file>.js.html` | Pretty-printed source, if `outputSourceFiles` is on |
| `styles/`, `scripts/`, `fonts/` | Assets for the template |
Giving modules their own pages
In an ES module project, jsdoc does not create a module page from export statements alone. Without a @module tag, your exported functions all land together in global.html, which is hard to browse in any project with more than a few files. Add a module tag as the first JSDoc comment in each file:
/**
* Price and tax helpers.
* @module pricing
*/
/**
* Calculates a price including tax.
* @param {number} price - The base price.
* @param {number} [taxRate=0.2] - Tax rate as a fraction.
* @returns {number} The price with tax applied.
*/
export function withTax(price, taxRate = 0.2) {
return price * (1 + taxRate);
}Now withTax appears on module-pricing.html under the name module:pricing.withTax, and the sidebar lists pricing under "Modules". Use the same full name to link to it from another file: {@link module:pricing.withTax}.
Private and internal symbols
Symbols tagged @private are left out by default. This lets you document internal helpers for maintainers without publishing them. Build an internal edition with -p or "private": true under opts. Symbols tagged @protected and @package are included by default. Control them with the --access option, for example --access public to show only public symbols.
Changing the Template
The default template works but looks dated. Community templates are npm packages that you point jsdoc at with -t or opts.template. For example, with docdash:
npm install --save-dev docdash
npx jsdoc -c jsdoc.json -t node_modules/docdashOr in the configuration file:
{
"opts": {
"destination": "docs",
"recurse": true,
"template": "node_modules/docdash"
}
}Templates often read their own settings from the templates section, under a key named after the template (for docdash it is "docdash"). Read the template's README for its options. Before you pick one, check that it is still maintained and supports the jsdoc major version you use. An abandoned template is a common reason a jsdoc upgrade breaks the build.
Debugging with --explain
When a symbol is missing, has the wrong name, or shows up on the wrong page, look at the doclets before you blame the template:
npx jsdoc src/pricing.js -X > doclets.jsonEach object in the output has fields such as longname, kind, memberof, params, and undocumented. Search for your symbol's name. If its longname is withTax instead of module:pricing.withTax, the @module tag is missing or is not the first comment in the file. If undocumented is true, jsdoc saw the code but found no JSDoc comment attached to it. A common cause is a blank line or a regular // comment between the /** */ block and the declaration.
Common Errors and Their Causes
"There are no input files to process"
Either the paths are wrong, -r is missing and all code sits in subdirectories, or includePattern filters out your files (for example, .mjs). Check source.include and the pattern first.
Types that TypeScript understands but jsdoc does not
jsdoc has its own type parser, and it is older than TypeScript's. It handles everything covered in the type expression chapter: unions, arrays, records, nullable and optional markers. It does not understand TypeScript-only syntax such as import('./user.js').User, conditional types, keyof, or { [key: string]: number } index signatures. Depending on the construct, jsdoc reports an "Invalid type expression" error or prints the type badly.
Unknown tags
By default, jsdoc allows tags it does not recognize and ignores them. If you set "tags": { "allowUnknownTags": false }, a typo such as @retruns becomes an error. This strict setting catches mistakes, but it also rejects tags meant for other tools. The "dictionaries": ["jsdoc", "closure"] setting controls which built-in tag sets are recognized.
Warnings that do not fail the build
jsdoc logs many problems as warnings and still exits successfully. In continuous integration, add --pedantic so malformed comments fail the job instead of shipping a broken page:
{
"scripts": {
"docs": "jsdoc -c jsdoc.json",
"docs:check": "jsdoc -c jsdoc.json --pedantic -d /tmp/jsdoc-check"
}
}Publishing the Output
The docs directory is generated, so treat it like any other build output. The usual approach is to add it to .gitignore and have CI build and publish it, for example to GitHub Pages. If you publish from a docs folder on the main branch instead, rebuild it in the same commit as the code change. Otherwise the published site drifts behind the code. jsdoc does not delete stale files from the destination, so pages for renamed or removed symbols stay there. Clear the directory before each build:
{
"scripts": {
"predocs": "node -e \"require('fs').rmSync('docs', { recursive: true, force: true })\"",
"docs": "jsdoc -c jsdoc.json"
}
}npm runs predocs automatically before docs, so stale pages are removed every time.
Exercise
Your project keeps its code in src/core/*.mjs and src/util/*.mjs. Running npx jsdoc src -d docs reports "There are no input files to process." Name the two separate problems and write a jsdoc.json that fixes both.
Show answer
First, without -r (recurse), jsdoc reads only files directly inside src, and there are none there. Second, the default includePattern matches .js, .jsdoc, and .jsx, so .mjs files are skipped. Fix: { "source": { "include": ["src"], "includePattern": "\\.(js|mjs)$" }, "opts": { "destination": "docs", "recurse": true } }, then run npx jsdoc -c jsdoc.json.
Exercise
Every exported function in your ES module project appears on global.html, and the sidebar has no "Modules" section. What is missing, and how would you confirm the fix with --explain?
Show answer
The files have no @module tag. Add /** Description. @module name */ as the first JSDoc comment in each file. Run npx jsdoc path/to/file.js -X and check that each function's longname now has the form module:name.functionName and that its memberof is module:name.
Exercise
A teammate's comment @param {import('./user.js').User} user passes tsc with checkJs but breaks npm run docs. Why, and what options do you have?
Show answer
jsdoc uses its own type parser, which does not support TypeScript's import() type syntax, so it reports an invalid type expression. You can stay within the type syntax both tools share, add a jsdoc plugin that rewrites import() types before parsing, or move to a TypeScript-aware generator such as TypeDoc if the project depends on TypeScript-only type syntax.