astro-better-code-snippet-extractor

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

Node 22.6+ compatibility

Version 0.2.1 fixes a crash on Node 22.6+ where ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING was thrown when Bluehawk loaded .d.ts files from node_modules. The fix strips type-stripping flags from NODE_OPTIONS before spawning the Bluehawk subprocess.

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
snippetstringBluehawk snippet ID to extract (omit to include the whole file)
langstringLanguage for syntax highlighting
titlestringFilename 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.