Skip to content

Instantly share code, notes, and snippets.

@JanMalch
Last active December 29, 2021 12:49
Show Gist options
  • Save JanMalch/a7c9df1d87b3e2209490714f2ade3d0e to your computer and use it in GitHub Desktop.
Save JanMalch/a7c9df1d87b3e2209490714f2ade3d0e to your computer and use it in GitHub Desktop.
Typedoc: Wrap example tag in codeblock
docs-example-plugin.js

WrapExampleInCodeBlockPlugin

The plugin automatically wraps the entire text of @example tags in a Markdown typescript code block, so the generated documentation properly renders the code.

I'm using this setup in my comparing library.

import { Application, Context, Converter, ReflectionKind } from 'typedoc';
/**
* A plugin that wraps the text of `@example` in a Markdown `typescript` code block.
*/
class WrapExampleInCodeBlockPlugin {
/**
* Initializes the plugin.
* @param typedoc The TypeDoc application.
*/
public initialize(typedoc: Readonly<Application>): void {
typedoc.converter.on(Converter.EVENT_RESOLVE_BEGIN, (c: Readonly<Context>) => this.onConverterResolveBegin(c));
}
/**
* Triggered when the TypeDoc converter begins resolving a project.
* @param context Describes the current state the converter is in.
*/
public onConverterResolveBegin(context: Readonly<Context>): void {
const project = context.project;
const reflections = [
// update if necessary!
...project.getReflectionsByKind(ReflectionKind.CallSignature),
...project.getReflectionsByKind(ReflectionKind.Class),
...project.getReflectionsByKind(ReflectionKind.Interface),
];
for (const reflection of reflections) {
if (reflection.comment != null && reflection.comment.hasTag('example')) {
const tag = reflection.comment.getTag('example')!;
tag.text = '\n```typescript\n' + tag.text.trim() + '\n```\n';
}
}
}
}
/**
* Initializes the plugin.
* @param app Reference to the application that is loading the plugin.
*/
export function load(app: Readonly<Application>): void {
new WrapExampleInCodeBlockPlugin().initialize(app);
}
{
"scripts": {
"predocs": "tsc docs-example-plugin.ts",
"docs": "typedoc",
}
}
{
"plugin": "./docs-example-plugin.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment