Unist Utility to Get Source Code

5.0.0 · active · verified Sun Apr 19

unist-util-source is a focused utility in the unified ecosystem designed to extract the original source code corresponding to a `unist` node or a specific position within a `VFile`. It is currently stable at version 5.0.0 and follows the unified collective's release cadence, which typically aligns major versions with Node.js LTS releases. Key differentiators include its tight integration with the `unist` specification and `vfile` for reliable positional data, its minimal API surface, and its commitment to modern JavaScript practices like being ESM-only and fully typed with TypeScript. It serves as a foundational building block for tools that need to represent parts of a parsed document back in their original textual form, such as linters, code formatters, or rich text editors displaying snippets.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to read a Markdown string, parse it into a unist tree using `mdast-util-from-markdown`, and then extract the source code for a specific `strong` node using `unist-util-source`.

import { fromMarkdown } from 'mdast-util-from-markdown';
import { read } from 'to-vfile';
import { source } from 'unist-util-source';

async function main() {
  const markdownContent = `> + **[Hello](./example)**\n>   world.`;
  // In a real scenario, you'd read from a file: const file = await read('example.md');
  // For a self-contained example, we'll create a VFile from a string.
  const file = { path: 'example.md', value: markdownContent };
  const tree = fromMarkdown(String(file.value));

  // Navigate to a specific node (e.g., the 'strong' node containing 'Hello')
  // This path depends on the specific Markdown content and parser output.
  // For '> + **[Hello](./example)**\n>   world.', a 'strong' node is deep inside a blockquote, list, listItem, paragraph.
  // This assumes a typical parsing output structure for the example given in docs
  const blockquote = tree.children[0]; // The blockquote node
  const listItem = blockquote.children[0]; // The list item within the blockquote
  const paragraph = listItem.children[0]; // The paragraph within the list item
  const strongNode = paragraph.children[0].children[0].children[0].children[0].children[0];

  if (strongNode) {
    console.log(`Source for strong node: "${source(file, strongNode)}"`);
  } else {
    console.log('Could not find the strong node.');
  }
}

main().catch(console.error);

view raw JSON →