TypeDoc Integration #

Reference docs for a TypeScript library usually go wrong in two ways: the docs drift from the source, and a broken example goes unnoticed.

@kawapress/plugin-typedoc is the TypeDoc integration of KawaPress: at build time it uses TypeDoc to read the exports and JSDoc of your TypeScript source and generates the reference pages directly, with no folder of generated .md files to commit. The same data also:

  • shows the signature of a function inside any article;
  • checks the code in @example tags, so a wrong example fails the build;
  • compares versions and lists what was added, changed, deprecated and removed;
  • packs the API into an Agent Skill that can be installed as it is.

The API reference of this site is generated by the plugin.

Install #

Shell
npm install --save-dev @kawapress/plugin-typedoc typedoc typescript

typedoc and TypeScript 6 are peer dependencies. TypeScript 7's native implementation does not offer the JavaScript API the analysis needs yet, so it is not supported.

TypeScript
import typedocPlugin from '@kawapress/plugin-typedoc'
import { nagi } from 'kawapress/nagi'

export default nagi({
  plugins: [
    typedocPlugin({
      entries: {
        'my-lib': '../src/index.ts',
        'my-lib/node': '../src/node.ts',
      },
    }),
  ],
})

The keys of entries are the module names readers write in import, the values are the entry source files relative to the site root. The pages:

Text
/api/                    Overview: one line per entry
/api/my-lib/             Module page: grouped by task, one line of name and summary per symbol
/api/my-lib/myFunction   Symbol details
/api/my-lib-node/        A `/` in the entry name becomes `-`
/api/changes             API changes (only when snapshots exist)

Every locale gets its own copy, for example /en/api/. The fixed texts of the pages ("Usage", "Parameters", "Returns" and so on) follow the locale: Chinese and English are built in and other languages fall back to English. The JSDoc itself has one language; write translations when a locale needs another.

These are ordinary Markdown pages, so the sidebar, search, sitemap, llms.txt and the per-page .md have them without extra work. The automatic sidebar sorts by path and does not know groups. To navigate by group, write module-level links for /api/ in themeConfig.sidebar, as this site does; the module pages show the groups of symbols.

Writing docs with JSDoc #

The first paragraph of a comment is the summary, shown on the module page and at the top of the details page; the rest is the body.

TypeScript
/**
 * Creates a site.
 *
 * The second paragraph says more and can link to another symbol with {@link SiteOptions}.
 * @usage Create by name
 * @param name - Name of the site.
 * @returns The new site.
 * @category Sites
 * @since 1.2.0
 * @example
 * ```ts
 * import { createSite } from 'my-lib'
 *
 * const site = createSite('docs')
 * ```
 */
export function createSite(name: string): Site
TagEffect
@category NamePuts the symbol in a group on the module page. Symbols without one are grouped by kind (functions, types, classes, variables) and come last. categoryOrder sets the order of groups.
@usage TitleNames an overload; the title of its usage tab.
@exampleAn example, type-checked at build time.
@since versionThe version that introduced it. Without it, the version of the earliest snapshot that has the symbol.
@deprecated noteA warning on the details page, a mark on the module page, and a line under "Deprecated" on the changes page.
@param, @returnsWhat a parameter is and what comes back, written on each overload.
@remarks, @seeThe "Notes" section of the page.
@defaultValueThe default of an object field.
{@link Symbol}A link to the details page of the symbol. When it cannot be resolved, it renders as inline code and the build warns with the source file and line.
@internal, @hidden, @ignoreKeeps the symbol out of the docs.

A comment with @packageDocumentation at the top of an entry file describes the module: its first paragraph appears on the overview and the whole text on the module page.

How a symbol page reads #

Readers arrive asking "how do I use this?", so a symbol page answers from top to bottom: what it does (one sentence), how to use it (an example to copy), what you pass in, what you get back, what to watch out for, and only then the full type signature.

The "Usage" section of a function has one group per overload: a title, its examples, its parameters and its return value. Parameters are explained right on the page. When a parameter is an object type (an inline object, or an interface or object type alias declared in the analysed sources, inherited members included), its fields are listed in place: name, whether it is optional, type, description and default, with no jump to another page. When a field is a method whose first parameter is such an object, that object's fields are expanded one level further, two levels at most.

With several overloads, each is a tab, and switching tabs swaps the example and the fields together. The title of a tab is its @usage text; without one it is the first sentence of the overload's comment when that is 40 characters or fewer, and a number ("Form 1") otherwise.

TypeScript
/**
 * Reads local files.
 * @usage Read local files
 * @example
 * ```ts
 * defineLoader({ load: ({ read }) => read('./a.txt') })
 * ```
 */
export function defineLoader<T>(loader: Loader<T>): Loader<T>
/**
 * Watches a set of files.
 * @usage Watch files
 */
export function defineLoader<T>(pattern: string, load: (files: string[]) => T): Loader<T>

Interfaces, types, classes and variables read the same way: summary, examples, "Fields" ("Members" for classes and enums), "Notes". A method shows a compact call signature and its description. The full declaration is folded at the end of the page; a type alias that is not an object type shows it open, because it is the content.

The field lists, the tabs and the folded signature are equivalent Markdown in the page .md and in llms-full.txt: one ### section per usage and nested lists for the fields.

Type-checked examples #

The ts and tsx blocks of an @example are written as twoslash code blocks on the page and compiled by Twoslash: a type error fails the build and names the symbol and the source file. On the page you can hover a variable to see its type.

An import of your own package in an example resolves like any module from the site root: install your package as a dependency of the docs site and the plugin does not rewrite paths. To show a type error on purpose, annotate it with Twoslash's @errors:

TypeScript
/**
 * @example
 * ```ts
 * // @errors: 2345
 * createSite(42)
 * ```
 */

nagi turns Twoslash on by default. When the site has not turned it on, examples render as plain code blocks and the build warns once.

Signatures in articles #

Write the ApiSignature tag in any Markdown page. of is module!Symbol:

Markdown
<ApiSignature of="kawapress!defineConfig" />

It renders from the same data as the details page, so it follows the source:

defineConfig
function defineConfig(config: KawapressConfig): KawapressConfig
Declares the site config in kawapress.config.ts. It only adds types.

When the name is unique across all entries you can leave out the module: <ApiSignature of="defineConfig" />. An unknown symbol, or a short name that exists in several modules, fails the build and names the page and the full form to write.

In the .md of a page and in llms-full.txt the tag becomes the same content as Markdown.

API changes and snapshots #

Each version keeps an API snapshot in the repository. The plugin compares neighbouring snapshots and writes the changes page: what was added, changed (old and new signature), deprecated and removed, per package and version, newest first.

Snapshots live in api-snapshots/<package>/<version>.json (change the folder with snapshotDir) as sorted JSON, easy to review in a PR. A snapshot records each symbol's kind, signatures, member signatures and whether it is deprecated, never its description, so editing only a comment is not an API change.

A build never writes snapshots. Generate them with the command:

Shell
npx kawapress-typedoc snapshot

Run it in the site root. It writes a snapshot for the package of each entry at the version in its current package.json, keeps an existing snapshot of that version, and overwrites it only with --force. Add it to your release process so snapshots enter the repository with the release commit.

The changes page (/api/changes) only exists when snapshots exist. It lists released versions only; the difference between the current source and the latest snapshot is not on the page and is printed as a summary in the console when a build or the dev server starts.

A symbol without @since shows the version of the earliest snapshot that has it. The oldest snapshot of a package is only a starting point and does not say when its symbols were added, so nothing is inferred from it.

Agent Skill #

With a skill option the build also produces a Skill that an Agent can install as it is:

TypeScript
typedocPlugin({
  entries: { 'my-lib': '../src/index.ts' },
  skill: {
    name: 'my-lib-api',
    description: 'Look up the my-lib API while writing code that uses it instead of guessing signatures.',
  },
})

The output sits under api/skill/:

  • SKILL.md: name and description come from the option; the body says when to use it and lists each entry with its reference file.
  • references/<entry>.md: every signature of the entry by category, with summaries, parameter notes and examples, compact and without page decoration.

To ship the same content inside your npm package, write it into a folder of the repository:

Shell
npx kawapress-typedoc skill --out skills/my-lib-api

An Agent reads from shallow to deep: the site's llms.txt, the module page, one symbol. Every layer is short.

Translating JSDoc #

When the site has a locale such as Chinese, the fixed texts of the pages follow it, but JSDoc lives in the source and has one language. Translations live in the site, apart from the source:

Text
api-i18n/zh-CN/my-lib.json          one file per entry
api-i18n/zh-CN/my-lib-node.json     the file name is the path segment of the entry

Change the folder with the translations option; the sub folder is the lang of the locale. A file records the English original and the translation of each text, by symbol and then by position:

JSON
{
  "createSite": {
    "summary": { "original": "Creates a site.", "text": "创建一个站点。" },
    "usage.0.title": { "original": "Create by name", "text": "按名字创建" },
    "usage.0.param.name": { "original": "Name of the site.", "text": "站点名。" },
    "usage.0.example.0": { "original": "```ts\ncreateSite('docs')\n```", "text": "```ts\n// 创建站点\ncreateSite('docs')\n```" }
  }
}

original is the English at the time and text the translation. Both are Markdown, and a {@link} written as [Name](api:my-lib!Name) keeps resolving to a page link. Translated examples are type-checked like any other, so keep the code unchanged.

PositionText
summary, description, deprecatedThe description and deprecation note of the symbol.
usage.<n>.title, .summary, .returnsTitle, description and return text of usage n.
usage.<n>.example.<m>Example m of usage n, as a whole Markdown text.
usage.<n>.param.<param>The description of a parameter.
usage.<n>.field.<param>.<field>A field of a parameter; add the field name for each level below, and for a function field add the name of its first parameter first, for example usage.0.field.loader.load.context.read.
member.<name>A member of an interface, class or enum; nested fields add names the same way.
example.<n>, see.<n>Examples and "see also" of symbols that are not functions.
entry.summary, entry.description, category.<category> under $moduleThe description of the entry and the titles of its categories.

A translation is used only when text is not empty, original matches the English in the source exactly, and there is no previous; otherwise that text shows in English. The build never fails for it and prints one line per entry and language:

Text
api-i18n/zh-CN/my-lib.json: 3 stale, 12 missing

"Missing" has no translation yet; "stale" means the English changed and the translation has not caught up. A language without a folder prints nothing.

Create and update the files with the command:

Shell
npx kawapress-typedoc translations

New texts are added with an empty text. When the English changed, original becomes the new English and the old translation moves to previous, so the translator can compare; the text counts as stale until text is updated and previous is removed. Keys that no longer exist are dropped. Files are written as two-space JSON in a stable order. --locale zh-CN handles one language, --list prints the keys that are missing or stale, and --check writes nothing and exits with an error when something is missing or stale, which fits CI later.

Options #

OptionDescription
entriesRequired. Keys are module names, values are entry source files relative to the site root.
tsconfigtsconfig for the analysis, relative to the site root. Default: the nearest one above the first entry.
routeWhere the API pages are mounted, default api/. Each locale gets a copy under its prefix.
localesGenerate pages for these locales only. Default: all.
categoryOrderOrder of @category groups; unlisted groups follow alphabetically and uncategorized symbols come last.
snapshotDirSnapshot folder relative to the site root, default api-snapshots.
skill{ name, description } to produce the Agent Skill. Off by default.
translationsFolder of the JSDoc translations, relative to the site root. Default api-i18n.

While developing #

Edit the source with the dev server running and the API pages and ApiSignature update. Each update is a full analysis; when one fails, the previous result stays and the error is reported. The first analysis happens when the page list is first needed. A large package takes a few seconds, and the first request of the dev server waits for it.

Limits #

  • Only entries with .ts source or .d.ts files are analyzed, not plain JavaScript.
  • The source and the packages imported in examples must resolve from the site; in a monorepo, make the package a dependency of the docs site.
  • The client code of the build contains neither typescript nor typedoc.

Edit this pageLast updated:

Comments