For AI agents: The complete documentation index is available at /llms.txt. A markdown version of this page is available at /build-tools/code-snippet-extractor.md.

Code Snippet Extraction

On this page

An integration and component for loading code snippets into Astro pages. Supports Bluehawk-annotated files (with // :snippet-start: / :snippet-end: markers) and plain source file inclusion.

Current version: 0.2.1 --npm

Installation

$ npm install astro-better-code-snippet-extractor @astrojs/prism

Setup

Register the integration

In astro.config.ts:

import { codeSnippetExtractor } from 'astro-better-code-snippet-extractor/integration.js';

export default defineConfig({
  integrations: [
    codeSnippetExtractor({
      sourcePaths: ['../my-app/src'],
    }),
  ],
});

Use the component in MDX

import ExtractedCode from 'astro-better-code-snippet-extractor/ExtractedCode.astro';

<ExtractedCode
  path="../my-app/src/auth/login.ts"
  snippet="loginExample"
  lang="typescript"
/>

Integration options

OptionTypeDefaultDescription
sourcePathsstring[][]Directories to scan for Bluehawk-annotated files
outputDirstring.astro/snippetsWhere to write extracted snippet files

ExtractedCode props

PropTypeDefaultDescription
pathstring(required)Path to the source file
snippetstring—Bluehawk snippet ID to extract (omit to include the whole file)
langstring—Language for syntax highlighting
titlestring—Filename label shown above the code block

Bluehawk annotations

Annotate source files with Bluehawk markers:

// :snippet-start: loginExample
async function login(username: string, password: string) {
  const response = await fetch('/api/login', {
    method: 'POST',
    body: JSON.stringify({ username, password }),
  });
  return response.json();
}
// :snippet-end:

The integration runs Bluehawk at build time to extract annotated regions. The ExtractedCode component then renders the result with syntax highlighting.