Remark Plugin to Import TypeScript Code

1.0.1 · active · verified Sun Apr 19

remark-typescript-code-import is a Remark plugin designed to extract and embed specific code snippets from TypeScript files directly into Markdown or MDX documents. It allows developers to import types, interfaces, functions, or other code blocks by referencing a file path and a specific symbol using a directive syntax (e.g., `::typescript{file="./Component.tsx#ComponentProps"}`). The plugin operates within the Unified ecosystem, requiring `remark-directive` to parse custom directives. Currently at version 1.0.1, it provides TypeScript types and supports Node.js >=16. Its primary differentiator is the targeted import of TypeScript-specific constructs, making it ideal for documentation where code examples need to be synchronized with actual source files without manual copying. Releases appear to be ad-hoc based on changes and fixes rather than a strict schedule.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the plugin with `remark` and `remark-directive` to import TypeScript code snippets into a Markdown file. It sets up example `.md` and `.tsx` files, then processes the Markdown to show the imported code blocks. It also illustrates the `rootDir` option.

import { remark } from 'remark';
import path from 'node:path';
import { readSync } from 'to-vfile';
import remarkDirective from 'remark-directive';
import remarkTypescriptCodeImport from 'remark-typescript-code-import';
import { writeFileSync, mkdirSync } from 'node:fs';

// Create dummy files for the example
mkdirSync('docs', { recursive: true });
writeFileSync('docs/example.md', '::typescript{file="./Component.tsx#ComponentProps"}\n::typescript{file="<rootDir>/src/types.ts#User"}');
writeFileSync('docs/Component.tsx', 'type ComponentProps = {\n  propA: string;\n}\n\nfunction Component(props: ComponentProps) {\n  // ...\n}');
mkdirSync('src', { recursive: true });
writeFileSync('src/types.ts', 'export type User = {\n  id: string;\n  name: string;\n};');

async function processMarkdown() {
  const result = await remark()
    .use(remarkDirective)
    .use(remarkTypescriptCodeImport, { rootDir: process.cwd() })
    .process(readSync(path.join(process.cwd(), 'docs', 'example.md')));

  console.log('--- Processed Markdown ---\n');
  console.log(String(result));
  console.log('\n--- End Processed Markdown ---');
}

processMarkdown();

view raw JSON →