导航菜单

文档网站部署和优化

构建与预览

  • 开发:pnpm dev
  • 构建:pnpm build
  • 预览:pnpm preview(本地验证构建产物)

常见托管方式

  • Cloudflare Pages:连接仓库,框架选 Astro 或自定义 pnpm install && pnpm build,输出目录 dist
  • Vercel/Netlify:同理设置构建命令与输出目录。
  • 自托管 Nginx/OSS/CDN:上传 dist/,配置静态根目录和缓存。

环境变量

  • 在云平台面板配置 PUBLIC_ 前缀变量(Astro 仅暴露 PUBLIC 开头变量给客户端)。
  • 构建时依赖的密钥只放服务端变量,不要暴露到前端。

Base 与路径

  • 若站点挂在子路径,astro.config.mjs 设置 base: '/docs',并确保静态资源引用使用 Astro.site/base 辅助。
  • 检查站内链接是否为绝对/相对的一致策略。

缓存与压缩

  • 开启 gzip/br 压缩(多数托管默认)。
  • HTML 短缓存或 no-cache,静态资源(CSS/JS/图片)使用指纹文件可长缓存。

部署前检查清单

  • 构建无报错,pnpm preview 正常。
  • 站内链接/锚点/图片均可访问。
  • SEO:<title>/<meta description> 完整,必要时加 sitemap/robots.txt。
  • 若用 Cloudflare Pages,确认 Functions 路由未与静态路径冲突。***

构建优化

1. 构建配置

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,
    // 优化输出
    format: 'file',
    // 启用资源压缩
    assets: true,
  },
  vite: {
    build: {
      // 代码分割策略
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor': ['react', 'react-dom'],
          },
        },
      },
    },
  },
});

2. 资源优化

图片处理

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

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

使用优化后的图片组件

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

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

部署配置

1. 静态部署

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. 自动部署

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

性能优化

1. 代码优化

懒加载组件

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

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

预加载关键资源

<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. 缓存策略

配置缓存控制

// 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 优化

添加 SEO 组件

---
// 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}>

监控和分析

1. 性能监控

添加 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() API
  navigator.sendBeacon('/analytics', body);
}

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

2. 错误跟踪

集成错误监控服务

// src/utils/errorTracking.js
export function initErrorTracking() {
  window.addEventListener('error', (event) => {
    // 发送错误信息到监控服务
    console.error('Captured error:', event.error);
  });

  window.addEventListener('unhandledrejection', (event) => {
    // 处理未捕获的 Promise 错误
    console.error('Unhandled rejection:', event.reason);
  });
}

最佳实践

  1. 部署流程

    • 使用持续集成/持续部署(CI/CD)
    • 实施自动化测试
    • 配置环境变量管理
  2. 性能优化

    • 实施渐进式增强
    • 优化关键渲染路径
    • 使用适当的缓存策略
  3. 监控和维护

    • 定期检查性能指标
    • 监控错误和异常
    • 及时更新依赖包

总结

通过本章的学习,你已经掌握了:

  1. 如何优化 Astro 文档网站的构建过程
  2. 部署网站到不同的托管平台
  3. 实施性能优化策略
  4. 设置监控和分析系统

这些知识将帮助你构建一个高性能、易维护的文档网站。记住,优化是一个持续的过程,要根据实际需求和用户反馈不断改进。

搜索