导航菜单

Data and Content Management

Content Collections

  • Define collections: defineCollection in src/content/config.ts with schema/types.
  • Type-safety: Zod/schema validates frontmatter and generates types.
  • Query: getCollection('posts') to read/filter/sort.
  • Example:
    // src/content/config.ts
    import { defineCollection, z } from 'astro:content';
    const posts = defineCollection({
      schema: z.object({
        title: z.string(),
        date: z.date(),
        tags: z.array(z.string()).optional(),
      }),
    });
    export const collections = { posts };
    

Data fetching

  • Static data: const data = await fetch(...) at top of the page—runs at build and writes into static HTML.
  • API integration: use fetch/await; if sources are unstable, move to onRequest (SSR) or incremental generation.
  • Dynamic import: const md = await import('../../data/foo.json'); bundles at build time.
  • Prefetch: for list+detail, prefetch lists at build and generate static detail pages.

Markdown/MDX enhancements

  • Frontmatter: store metadata (title/description/tags).
  • MDX: embed components for reusable UI (callouts, charts).
  • Highlighting: built-in code highlight or configure Shiki/Prism.
  • Custom components: import at top and map via export const components.

Images

  • Use <Image /> or @astrojs/image: multi-size, WebP, lazy-loading.
  • Set width/height/format to avoid shipping originals raw.
  • Configure remote domains allowlist for external images.

Content management practices

  • Structure by language/topic/year; semantic file names.
  • Tags/categories in frontmatter for filtering/search.
  • Related content via slug/ID (related posts, prev/next).
  • Search: generate static JSON index at build, query client-side, or use external search.

搜索