TypeDoc now lets us refer to parts of other files via {@includeCode}
. In this blog post, I explain how that works and why it’s useful.
Since version 0.27.7, TypeDoc lets us refer to parts of external files via the doc tag {@includeCode}
:
File util.ts
:
/**
* {@includeCode ./util_test.ts#utilFunc}
*/
function utilFunc(): void {}
Note the hash (#
) and the name utilFunc
after the path of the file: It refers to a region inside util_test.ts
. A region is a way to mark sequences of lines in a source file via comments. Regions are also supported by Visual Studio Code where they can be folded (documentation).
This is what the region inside util_test.ts
looks like:
test('utilFunc', () => {
//#region utilFunc
···
//#endregion utilFunc
});
The file names already suggest the use case for this feature: It enables us to publish documentation where all code examples (such as region utilFunc
) are tested.
In the past, TypeDoc only let us include full files, which meant one file per example – with test boilerplate showing up in the documentation.
File array.ts
:
/**
* Split `arr` into chunks with length `chunkLen` and return them
* in an Array.
* {@includeCode ./array_test.ts#arrayToChunks}
*/
export function arrayToChunks<T>(
arr: Array<T>, chunkLen: number
): Array<Array<T>> {
// ···
}
File array_test.ts
:
// ···
test('arrayToChunks', () => {
//#region arrayToChunks
const arr = ['a', 'b', 'c', 'd'];
assert.deepEqual(
arrayToChunks(arr, 1),
[['a'], ['b'], ['c'], ['d']],
);
assert.deepEqual(
arrayToChunks(arr, 2),
[['a', 'b'], ['c', 'd']],
);
//#endregion arrayToChunks
assert.deepEqual(
arrayToChunks(arr, 3),
[['a', 'b', 'c'], ['d']],
);
assert.deepEqual(
arrayToChunks(arr, 4),
[['a', 'b', 'c', 'd']],
);
assert.deepEqual(
arrayToChunks(arr, 5),
[['a', 'b', 'c', 'd']],
);
});
{@includeCode}