导航菜单

Documentation Site Deployment & Optimization

Build & preview

  • Dev: pnpm dev
  • Build: pnpm build
  • Preview: pnpm preview (validate build locally)

Common hosting options

  • Cloudflare Pages: connect repo, framework Astro or custom pnpm install && pnpm build, output dist.
  • Vercel/Netlify: same idea—set build command and output dir.
  • Self-hosted Nginx/OSS/CDN: upload dist/, set static root and caching.

Environment variables

  • Set PUBLIC_ prefixed vars in the platform console (Astro only exposes PUBLIC vars to the client).
  • Keep build-time secrets on the server side; do not expose them to the frontend.

Base & paths

  • If hosted under a subpath, set base: '/docs' in astro.config.mjs and ensure static refs use Astro.site/base helpers.
  • Check consistency of absolute vs relative internal links.

Caching & compression

  • Enable gzip/br (most hosts default).
  • Short/no-cache for HTML; long-cache for fingerprinted CSS/JS/images.

Pre-deploy checklist

  • Build passes, pnpm preview works.
  • All internal links/anchors/images resolve.
  • SEO: <title>/<meta description> set; add sitemap/robots.txt if needed.
  • On Cloudflare Pages, ensure Functions routes don’t collide with static paths.***

Build optimizations

1) Build config

Tweak astro.config.mjs:

import HeadingWithIconH2 from '@/components/mdx/HeadingWithIconH2.astro';

export const components = {
  h2: HeadingWithIconH2,
};
import { defineConfig } from 'astro/config';

export default defineConfig({
  build: {
    incremental: true, // enable incremental builds
    format: 'file',    // optimize output format
    assets: true,      // enable asset compression
  },
  vite: {
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom'],
          },
        },
      },
    },
  },
});

2) Asset optimizations

Image processing

// astro.config.mjs
import image from '@astrojs/image';

export default defineConfig({
  integrations: [
    image({
      serviceEntryPoint: '@astrojs/image/sharp',
      cacheDir: './.cache/image',
      logLevel: 'debug',
    }),
  ],
});

Use optimized image component

---
import { Image } from '@astrojs/image/components';
---

<Image
  src={import('../assets/hero.png')}
  alt="Hero image"
  width={800}
  height={400}
  format="webp"
  quality={80}
/>

Deployment config

1) Static deploy

Netlify

# netlify.toml
[build]
  command = "npm run build"
  publish = "dist"

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

Vercel

// vercel.json
{
  "buildCommand": "npm run build",
  "outputDirectory": "dist",
  "framework": "astro"
}

2) Automated deploy

GitHub Actions

# .github/workflows/deploy.yml
name: Deploy Documentation

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Build site
        run: npm run build
      
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist

Performance optimization

1) Code optimizations

Lazy-load components

// src/components/HeavyComponent.astro
import { lazy } from 'astro/components';

const Comments = lazy(() => import('../components/Comments.astro'));

Preload critical assets

<head>
  <link rel="preload" href="/fonts/custom-font.woff2" as="font" type="font/woff2" crossorigin>
  <link rel="preconnect" href="https://api.your-service.com">
</head>

2) Cache strategies

Configure cache-control

// astro.config.mjs
export default defineConfig({
  headers: {
    '/*.{js,css,jpg,jpeg,png,gif,woff,woff2}': [
      {
        key: 'Cache-Control',
        value: 'public, max-age=31536000, immutable',
      },
    ],
  },
});

3) SEO

Add an SEO component

---
// src/components/SEO.astro
interface Props {
  title: string;
  description: string;
  image?: string;
}

const { title, description, image } = Astro.props;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<meta name="description" content={description}>
<meta property="og:title" content={title}>
<meta property="og:description" content={description}>
<meta property="og:url" content={canonicalURL}>
{image && <meta property="og:image" content={image}>}
<meta name="twitter:card" content="summary_large_image">
<link rel="canonical" href={canonicalURL}>

Monitoring & analytics

1) Performance tracking

Track Web Vitals

// src/utils/vitals.js
import { onCLS, onFID, onLCP } from 'web-vitals';

function sendToAnalytics({ name, delta, id }) {
  const body = JSON.stringify({ name, delta, id });
  
  navigator.sendBeacon('/analytics', body);
}

export function reportWebVitals() {
  onCLS(sendToAnalytics);
  onFID(sendToAnalytics);
  onLCP(sendToAnalytics);
}

2) Error tracking

Integrate error monitoring

// src/utils/errorTracking.js
export function initErrorTracking() {
  window.addEventListener('error', (event) => {
    console.error('Captured error:', event.error);
  });

  window.addEventListener('unhandledrejection', (event) => {
    console.error('Unhandled rejection:', event.reason);
  });
}

Best practices

  1. Deployment

    • Use CI/CD
    • Automate tests
    • Manage environment variables
  2. Performance

    • Progressive enhancement
    • Optimize critical render path
    • Apply proper cache strategy
  3. Monitoring & maintenance

    • Track performance regularly
    • Monitor errors/exceptions
    • Keep dependencies up to date

Summary

You now know how to:

  1. Optimize the build process for an Astro docs site
  2. Deploy to multiple hosting platforms
  3. Apply performance optimization strategies
  4. Set up monitoring and analytics

Optimization is continuous—iterate based on real needs and user feedback.

搜索