• Stars
    star
    129
  • Rank 279,262 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated almost 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

remark-typescript-tools

What is it?

remark-typescript-tools contains two remark plugins to use TypeScript code with remark, to generate better documentation.

Currently it is aimed at docusaurus, but already pretty configurable. And it's open source, pull requests for more configuration options are always welcome ;)

transpileCodeblocks

The transpileCodeblocks plugin will transpile all your ts-typed codeblocks to JavaScript and displays them side-by-side in tabs.

So

```ts
import { createAction, createReducer } from '@reduxjs/toolkit';

const increment = createAction<number>('counter/increment');
const decrement = createAction<number>('counter/decrement');

const counterReducer = createReducer(0, (builder) => {
  builder.addCase(increment, (state, action) => state + action.payload);
  builder.addCase(decrement, (state, action) => state - action.payload);
});
```

will be rendered to this:

an animations of tabs switching from TypeScript to JavaScript and back

It will validate the TypeScript on compilation, so your docs will be guaranteed to actually be runnable. It can even work against your library source code, which means that any PR that requires an update to your documentation will already get noticed in CI.

an image of a compilation error

Also, your examples can contain virtual files, importing from each other and you can even hide some of these virtual files, if they are not relevant for the example, but necessary for you to have valid code.

```ts
// file: reducers.ts noEmit
import { Reducer } from '@reduxjs/toolkit';
declare const rootReducer: Reducer<{}>;
export default rootReducer;

// file: store.ts
import { configureStore } from '@reduxjs/toolkit';

import rootReducer from './reducers';

const store = configureStore({ reducer: rootReducer });
```

linkDocblocks

This plugin allows you to link to sections of your source code's Docblocks, making sure that your documentation is up-to-date with your code.

So assuming this source code:

/**
 * Interface Test!
 * @remarks
 * Some more infos.
 */
export interface Test {
  /**
     * This is a function
     * @remarks
     * And it is nested!
     * @overloadSummary
     * Also, this is a special overload
     * @overloadRemarks
     * With some more description
     * @param foo - some info about the first parameter
     * @example
```ts
console.log("test")
```
     */
  nestedFunction(foo: string): void;
  /**
     * This is a function
     * @remarks
     * And it is nested!
     * @overloadSummary
     * Also, this is a special overload that takes a second parameter
     * @overloadRemarks
     * With some more extra description
     * @param foo - some info about the first parameter
     * @param bar - and some info about the second parameter
     * @example
```ts
console.log("test")
```
     */
  nestedFunction(foo: string, bar: number): void;
}

the markdown code

# Infos about Test

[summary](docblock://test/linkDocblocks.test.ts?token=Test)

## Some more remarks

[remarks](docblock://test/linkDocblocks.test.ts?token=Test)

would result in

# Infos about Test

Interface Test!

## Some more remarks

Some more infos.

And you can also link to nested identifiers or function overloads:

# Infos about Test.nestedFunction

[summary,remarks](docblock://test/linkDocblocks.test.ts?token=Test.nestedFunction)

# Overload 0

[overloadSummary,params,overloadRemarks,examples](docblock://test/linkDocblocks.test.ts?token=Test.nestedFunction&overload=0)

# Overload 1

[overloadSummary,params,overloadRemarks,examples](docblock://test/linkDocblocks.test.ts?token=Test.nestedFunction&overload=1)

will result in

# Infos about Test.nestedFunction

This is a function

And it is nested!

# Overload 0

Also, this is a special overload

#### Parameters:

- **foo** some info about the first parameter

With some more description

\`\`\`ts
console.log(\\"test\\")

\`\`\`

# Overload 1

Also, this is a special overload that takes a second parameter

#### Parameters:

- **foo** some info about the first parameter
- **bar** and some info about the second parameter

With some more extra description

\`\`\`ts
console.log(\\"test\\")

\`\`\`

Of course, you can combine this with transpileCodeblocks, so your examples from your comments from your source code will be actually type-checked against your source code!

Usage with Docusaurus:

We are using the plugins like this over in reduxjs/toolkit:

// site configuration options.
const { resolve } = require('path');
const {
  linkDocblocks,
  transpileCodeblocks,
} = require('remark-typescript-tools');

module.exports = {
  presets: [
    [
      '@docusaurus/preset-classic',
      {
        docs: {
          remarkPlugins: [
            [
              linkDocblocks,
              {
                extractorSettings: {
                  tsconfig: resolve(__dirname, '../docs/tsconfig.json'),
                  basedir: resolve(__dirname, '../src'),
                  rootFiles: ['index.ts'],
                },
              },
            ],
            [
              transpileCodeblocks,
              {
                compilerSettings: {
                  tsconfig: resolve(__dirname, '../docs/tsconfig.json'),
                  externalResolutions: {
                    '@reduxjs/toolkit': {
                      resolvedPath: resolve(__dirname, '../src'),
                      packageId: {
                        name: '@reduxjs/toolkit',
                        subModuleName: 'index.ts',
                        version: '1.0',
                      },
                    },
                  },
                },
              },
            ],
          ],
        },
      },
    ],
  ],
};

In addition to that, transpileCodeblocks takes these options:

import type { Node } from 'unist';
import type { VFile } from 'vfile';

export interface TranspileCodeblocksSettings {
  compilerSettings: CompilerSettings;
  postProcessTranspiledJs?: PostProcessor;
  postProcessTs?: PostProcessor;
  assembleReplacementNodes?: (
    node: CodeNode,
    file: VFile,
    virtualFolder: string,
    virtualFiles: Record<string, VirtualFile>,
    transpilationResult: Record<string, TranspiledFile>,
    postProcessTs: PostProcessor,
    postProcessTranspiledJs: PostProcessor
  ) => Node[];
}

interface CompilerSettings {
  tsconfig: string;
  externalResolutions: Record<string, ExternalResolution>;
  /**
   * Allows transforming the virtual filepath for codeblocks.
   * This allows the files to resolve node modules from a different location
   * to their own directory.
   */
  transformVirtualFilepath?: (filepath: string) => string;
}

interface CodeNode extends Node {
  lang: string;
  meta: string;
  value: string;
  indent: number[];
}

export interface VirtualFile {
  code: string;
  skip?: boolean;
}

export type VirtualFiles = Record<string, VirtualFile>;

type PostProcessor = (
  files: VirtualFiles,
  parentFile?: string,
  defaultProcessor?: PostProcessor
) => VirtualFiles;

export interface TranspiledFile extends VirtualFile {
  diagnostics: Array<Diagnostic>;
}

export type TranspiledFiles = Record<string, TranspiledFile>;

More Repositories

1

ssr-experiments

TypeScript
76
star
2

ts-deep-extract-types

TypeScript
41
star
3

use-local-slice

A react hook to use reducers for local state in a typesafe way, with an API like createSlice from redux-starter-kit and immer integration.
TypeScript
41
star
4

rehackt

JavaScript
23
star
5

ts-version

A little utility type package that allows you to access the current TypeScript version from your types.
TypeScript
17
star
6

ssr-only-secrets

This package provides a way to pass secrets from Server Components into the SSR-run of Client Components, without them being accessible in the browser.
TypeScript
15
star
7

format-with-prettier

TypeScript
13
star
8

egghead-rtk-query-basics

TypeScript
12
star
9

msw-reqres-in-mock

TypeScript
7
star
10

eldo

elevated "do" - sudo for windows
C#
7
star
11

rtkq-performance-testbench

TypeScript
7
star
12

generator-webext-typescript

generates a basic firefox webextension with typescript support
JavaScript
6
star
13

talk-ijs_london-state_of_react_state_2019

JavaScript
6
star
14

cli-mqtt-chatclient

TypeScript
5
star
15

tiled-canvas

This library allows rendering of TileMaps in the json export format of the "Tiled" editor.
TypeScript
4
star
16

frankenjs-22-07

What's up with Redux?
TypeScript
3
star
17

testable-ts

Nix
2
star
18

phryneas

2
star
19

ark_replace_vanilla_engrams

replace ark vanilla engrams with s+ engrams
HTML
2
star
20

react-advanced-talk-suspense-streaming-ssr

TypeScript
2
star
21

use-cached-fetch

A helper library that builds upon react-async's useAsync method to provide a useful asynchronous fetch hook with a shared cache between your components.
TypeScript
1
star
22

webpack-demo

for devcamp 2018
JavaScript
1
star
23

react-cli-gameoflife

TypeScript
1
star
24

loggedPDO

Class extending the php PDO Class for logging purpose
PHP
1
star
25

2019-04-05-developercamp-react-testing-session

JavaScript
1
star
26

postprocess-profile-sourcemaps

JavaScript
1
star
27

opendata-europawahl-wuerzburg

just some fiddling around
HTML
1
star
28

nix-help-generator

very WIP. one day this should generate a help for nix functions (especially lib), parsed from the source
ANTLR
1
star
29

reproduction-non-rollup-types

JavaScript
1
star
30

reproduction-expo-19997

https://github.com/expo/expo/issues/19997
JavaScript
1
star
31

react-19-reproduction-slow-tests

TypeScript
1
star
32

codetalks-ecmascript-evolving

ECMAScript as an evolving language
JavaScript
1
star
33

ansible-vagrant-workshop

Ruby
1
star
34

pentagame

just some fiddling around
TypeScript
1
star
35

react-days-2022-modern-redux-workshop

TypeScript
1
star
36

postgraphile-audit-plugin-demo-project

PLpgSQL
1
star
37

ct_webdev_redux_2022

Redux im Jahr 2022 - alles anders?
TypeScript
1
star
38

remix-apollo-stream-example

TypeScript
1
star