Code Snippet

Importing and displaying source code from your project.

Usage

Add the CodeSnippet component

components/content/CodeSnippet.vue
<template>
  <MDC v-if="loadedCode" :value="md" class="[&:not(:first-child)]:mt-5" />
  <UiAlert v-else variant="destructive">
    <UiAlertTitle>Error</UiAlertTitle>
    <UiAlertDescription>
      Cannot load code: <ProseCodeInline>{{ file || url }}</ProseCodeInline>
    </UiAlertDescription>
  </UiAlert>
</template>

<script setup lang="ts">
const { file, url, language, title, highlights, meta, start, offset } = defineProps<{
  file?: string;
  url?: string;
  language: string;
  title?: string;
  highlights?: string;
  meta?: string;
  start?: number;
  offset?: number;
}>();

const loadedCode = ref('');

const rawFiles = import.meta.glob([
  // Path you want to import
], {
  query: '?raw',
  import: 'default',
});

if (file) {
  const importer = rawFiles[file];
  if (importer) {
    loadedCode.value = (await importer()) as string;
  }
} else if (url) {
  try {
    const data = await $fetch(url, { parseResponse: txt => txt });
    if (data) {
      loadedCode.value = data as string;
    }
  } catch {}
}

if (loadedCode.value && start && offset) {
  const lines = loadedCode.value.split('\n');
  loadedCode.value = lines.slice(Number(start || 1) - 1, Number(start || 1) - 1 + Number(offset)).join('\n');
}

const md = `
::div
\`\`\`\`${language} ${title && `[${title}]`} ${highlights && `{${highlights}}`} ${meta || ''}
${loadedCode.value}
\`\`\`\`
::
`;
</script>

Add paths you want to import

Use the Glob Import pattern to add paths.

Line 25 to 30 in CodeSnippet.vue
const rawFiles = import.meta.glob([
  // Path you want to import
  // e.g.
  '@/examples/**/*.{vue}',
], {
  query: '?raw',
  import: 'default',
});

Use in markdown files

::code-snippet
---
file: /examples/file.vue
language: vue
---
::

Highlighting Lines

::code-snippet
---
file: /examples/file.vue
language: vue
title: File
highlights: 9-11
meta: line-numbers height=300
---
::

Translates to:

````ts [File] {9-11} line-numbers height=300
// code imported from /examples/file.vue
````

Using Offset Props

::code-snippet
---
file: /examples/file.vue
language: vue
start: 6
offset: 4
---
::

Fetching From a Remote URL

::code-snippet
---
url: https://raw.githubusercontent.com/ZTL-UwU/shadcn-docs-nuxt/refs/heads/main/pages/index.vue
language: vue
---
::

Props

filestring
The path to the imported file
urlstring
A remote URL to fetch the code from
titlestring
Code block title
languagestring
Code block highlight language
highlightsstring
Code block highlights lines
metastring
Code block meta
startnumber
Starting line index
offsetnumber
Number of lines to display from start