跳到主要内容

更快地发布代码,而不是更慢的网站

使用 AI 自动监控性能指标,在分支之间运行 A/B 测试,并根据 Netlify Analytics 的真实用户数据获取可操作的优化建议
新的 Netlify Mission Control 集成 为部署自动化实现了 持续 AI——AI 代理自主管理部署、监控网站性能并响应部署事件。本秘籍侧重于基于 CLI 的性能优化工作流,但您也可以通过 Mission Control 部署自主部署代理。入门: 使用本秘籍了解 Netlify MCP 的基本原理,然后启用 Mission Control,在您的组织中部署自主部署管理代理。
您知道吗? Netlify 不仅仅是静态托管!它还提供本指南将向您展示如何使用 Continue CLI 以自然语言利用这些功能!

你将学到什么

本手册将教您如何

先决条件

快速设置

Netlify 开发规则捆绑包包括以下护栏
  • 正确的 .gitignore 配置
  • 函数结构和位置
  • 边缘函数约束
  • 本地开发最佳实践
对于所有选项,首先
1

安装 Continue CLI

curl -fsSL https://raw.githubusercontent.com/continuedev/continue/main/extensions/cli/scripts/install.sh | bash
2

安装 Netlify CLI

  1. 安装 Netlify CLI:npm i -g netlify-cli
  2. 使用 Netlify 进行身份验证:netlify login

Netlify 持续 AI 工作流选项

🚀 最快的成功之路

跳过手动设置,使用我们预构建的 Netlify 持续 AI 代理,它包含优化的提示、规则和 Netlify MCP,以获得更一致的结果。
完成上述 快速设置 后,您有两种入门途径
要使用预构建代理,您需要满足以下任一条件:
  • Continue CLI 专业版计划,附带模型插件,或
  • 您自己的 API 密钥 已添加到 Continue Mission Control 秘密。代理将自动检测并使用您的配置以及 Netlify MCP 进行部署操作。

性能优化步骤

第 1 步:基线性能指标

使用 cn CLI 建立您当前的性能基线
# Start cn in TUI mode
cn

# Then ask:
"Show my site's Core Web Vitals and build times"
首先在计划模式下测试:在进行可能影响您网站的性能优化之前,请在计划模式下测试您的提示(请参阅计划模式指南;按 Shift+Tab 切换模式)。这会向您展示代理将执行的操作,而不会实际执行它。例如:“设置主分支和功能分支之间的 A/B 测试并进行性能监控”
Netlify 自动跟踪
  • 构建性能:编译时间、缓存命中
  • 运行时性能:核心 Web 指标、交互时间
  • 资源使用:带宽、函数执行时间

第 2 步:A/B 测试分支性能

比较分支之间的性能
# In cn TUI mode:
"Set up A/B test between main and feature branch on Netlify:
- Split traffic 50/50 between branches
- Track Core Web Vitals for each variant
- Monitor conversion metrics and bounce rate
- Enable analytics to measure performance impact
- Configure cookie-based visitor persistence
- Set test duration for 1000 unique visitors
- Auto-conclude test when statistical significance reached
Report winner based on performance + conversion metrics"
增强分析:将 Netlify 的 A/B 测试与 PostHog 会话记录相结合,不仅了解哪个变体表现更好,还了解用户行为差异的原因。请参阅我们的 PostHog 会话分析指南,设置会话跟踪并创建完整的持续 AI 分析工作流。

第 3 步:使用 Netlify 进行高级构建优化

利用 Netlify 强大的构建功能,显著缩短构建时间
# In cn TUI mode:
"Optimize my Netlify build performance using these features:

1. Enable Netlify Cache Plugin for dependency caching
   - Configure @netlify/plugin-cache for node_modules
   - Set up custom cache directories for .next/cache or .nuxt
   - Enable Gatsby's incremental builds if applicable

2. Set up Build Plugins from Netlify's ecosystem:
   - Install @netlify/plugin-lighthouse for performance monitoring
   - Add netlify-plugin-checklinks to prevent broken links
   - Configure netlify-plugin-submit-sitemap for SEO

3. Implement Conditional Builds:
   - Skip builds when only docs change (ignore: /docs/**)
   - Use build.ignore script for custom logic
   - Set up monorepo-specific build triggers

4. Configure concurrent builds for monorepos
   - Set base directory per package
   - Use pnpm workspaces or yarn workspaces

Show me the netlify.toml configuration and explain each optimization"
您获得的 Netlify 构建功能:这些功能可以将大多数项目的构建时间缩短 50-70%!
发现更多优化提示! Netlify 社区在其支持指南:如何优化我的 Netlify 构建时间中记录了数十种构建优化策略。使用本指南作为本秘籍未涵盖的 cn CLI 提示的灵感,例如:
  • “将我的构建配置为自动跳过 Dependabot PR”
  • “为仅限文档的更改设置自定义忽略模式”
  • “优化我的 Contentful webhook 以防止重复构建”
  • “向我展示如何使用构建钩子而不是自动 git 触发器”
  • “帮助我根据构建性能选择 Astro 和 Hugo”
社区指南包含您可以转换为 AI 辅助解决方案的真实场景——只需描述您想要实现的目标,让 cn CLI 处理实现!

第 4 步:使用 Netlify 内置工具进行包分析

使用 Netlify 的包分析器和优化功能
# In cn TUI mode:
"Analyze and optimize my bundle using Netlify's tools:

1. Enable Netlify Bundle Analyzer:
   - Add @netlify/plugin-bundle-analyzer to plugins
   - Configure size thresholds in netlify.toml
   - Generate visual bundle reports

2. Set up Asset Optimization:
   - Enable automatic JS minification
   - Configure CSS optimization
   - Turn on HTML minification
   - Set up image processing pipeline

3. Implement Smart Code Splitting:
   - Analyze current chunks with the bundle analyzer
   - Identify components over 50KB for splitting
   - Configure webpack/vite for optimal chunking
   - Set up route-based code splitting

4. Configure Netlify's CDN for optimal delivery:
   - Set cache headers for static assets
   - Enable Brotli compression
   - Configure edge caching rules

Generate a full report with before/after bundle sizes"

Netlify 的性能武器库

通过 Netlify MCP 可用的功能:

第 5 步:图片优化

优化图像以获得更好的性能
# In cn TUI mode:
"Set up Cloudinary image optimization for my Netlify site:
- Install @cloudinary/netlify-plugin via MCP
- Auto-convert images to WebP with fallbacks
- Generate responsive sizes (320w, 640w, 1024w, 1920w)
- Add lazy loading for all images
- Configure blur-up placeholders
- Update netlify.toml with Cloudinary settings
Target: Reduce image payload by 60-80% and improve LCP"

持续性能监控

第 6 步:使用 Lighthouse CI 强制执行性能预算

通过自动化测试设置和执行性能预算
# In cn TUI mode:
"Set up Lighthouse CI with performance budgets for my Netlify site:

Requirements:
- LCP must be < 2.5 seconds
- JavaScript bundle must be < 200KB
- Total size < 500KB
- Performance score >= 90

Setup needed:
1. Install @lhci/cli and @netlify/plugin-lighthouse
2. Create lighthouserc.js with these budget assertions
3. Configure netlify.toml to run checks on all deploys
4. Add GitHub status checks to block PRs that exceed budgets
5. Create performance dashboard at /lighthouse-reports

Please configure the complete Lighthouse CI setup with these budgets."
此全面设置将自动测试每个部署预览和生产部署,阻止任何违反性能预算的更改。

第 7 步:使用 Netlify Analytics 进行真实用户监控

利用 Netlify 的内置分析并集成高级 RUM 解决方案
# In cn TUI mode:
"Set up comprehensive Real User Monitoring for my Netlify site:

1. Configure Netlify Analytics Pro (requires Pro account):
   - Set up server-side analytics (no JS required)
   - Track Core Web Vitals (LCP, FID, CLS, INP)
   - Monitor top pages by performance score
   - Create custom performance alerts
   - Configure weekly performance reports

2. Integrate Web Vitals tracking:
   - Install web-vitals library for detailed metrics
   - Send metrics to Netlify Functions endpoint
   - Store performance data in Netlify Blobs
   - Create performance dashboard at /metrics

3. Set up Performance Alerts:
   - Alert when P75 LCP > 3 seconds
   - Notify if CLS increases by 20%
   - Monitor JavaScript error rates
   - Track 404s and broken resources
   - Send alerts to Slack via Netlify Functions

4. Configure Geographic Performance Monitoring:
   - Use Netlify Edge Functions to track region-specific metrics
   - Identify slow regions with Edge geo data
   - Compare performance across CDN nodes
   - Optimize edge caching for slow regions

5. Create Custom Performance Dashboard:
   - Build dashboard page using Netlify Functions
   - Display real-time Core Web Vitals
   - Show performance trends over time
   - Include browser and device breakdowns

Show me the complete implementation with all code and configurations"
注意:Netlify Analytics Pro 需要付费的 Netlify Pro 账户(每个站点每月 19 美元)。上面的提示假设您拥有此计划。对于免费套餐用户,请重点关注步骤 2-5,这些步骤使用 Netlify Functions 和 Edge Functions 构建自定义分析。
Netlify Analytics 优势:与 Google Analytics 不同,Netlify Analytics
  • 不会减慢您的网站速度(服务器端)
  • 捕获 100% 的流量(无广告拦截器)
  • 尊重用户隐私(无 cookie)
  • 单独显示机器人流量
专业提示 将 Netlify Analytics 与 Edge Functions 结合使用,创建一个强大的 RUM 解决方案,该解决方案
  • 按用户细分跟踪性能
  • A/B 测试性能优化
  • 根据连接速度个性化内容
  • 自动为慢速连接提供更轻量的资产

自动化性能检查

添加 GitHub Secrets

导航到 Repository Settings → Secrets and variables → Actions 并添加
  • CONTINUE_API_KEY:您的 Continue API 密钥,来自 continue.dev/settings/api-keys
  • NETLIFY_AUTH_TOKEN:您的 Netlify 个人访问令牌
  • NETLIFY_SITE_ID:您的 Netlify 站点 ID

GitHub Actions 性能卫士

阻止降低性能的 PR
name: Performance Check

on:
  pull_request:

jobs:
  performance:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Install Continue CLI
        run: |
          npm install -g @continuedev/cli
          echo "✅ Continue CLI installed"

      - name: Authenticate Continue CLI
        env:
          CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
        run: |
          cn auth login --api-key "$CONTINUE_API_KEY"
          echo "✅ Continue CLI authenticated"

      - name: Deploy and Test Performance
        id: perf
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
        run: |
          echo "🚀 Deploying PR preview and analyzing performance..."
          cn -p "Deploy PR preview and run Lighthouse.
                 Compare scores with main branch.
                 Output JSON with score deltas." > performance.json

      - name: Comment Performance Results
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const perf = JSON.parse(fs.readFileSync('performance.json'));

            const emoji = perf.score_delta < -10 ? '🔴' :
                         perf.score_delta < 0 ? '🟡' : '🟢';

            const comment = `## ${emoji} Performance Impact

            | Metric | Main | PR | Delta |
            |--------|------|----|---------|
            | Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} |
            | LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s |
            | Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB |

            ${perf.score_delta < -10 ? '⚠️ **This PR significantly degrades performance. Please optimize before merging.**' : ''}

            [View Full Report](${perf.report_url})`;

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });

            // Fail check if performance degrades significantly
            if (perf.score_delta < -10) {
              core.setFailed('Performance degraded by more than 10 points');
            }
此工作流将
  • 如果性能得分下降 >10 分,则阻止合并
  • 对任何性能退化发出警告
  • 通过绿色指示器庆祝改进

本地性能测试

第 8 步:本地性能测试

在部署前测试性能
# In cn TUI mode:
"Run production build and measure bundle sizes"

第 9 步:预提交性能检查

在性能回归发生之前阻止它们
# In cn TUI mode:
"Add pre-commit hooks for bundle size limits"

性能故障排除

调试性能问题

识别并修复性能瓶颈
# In cn TUI mode:
"Why did my performance score drop?"

性能问题快速修复

问题快速修复命令(在 cn TUI 中)
慢 LCP“预加载关键资源”
高 CLS“为图像添加尺寸属性”
大包“实现代码分割”
慢速构建“启用构建缓存”
缓存不良“配置缓存头”

您已完成的任务

性能优先开发

您已构建了一个 AI 驱动的性能优化系统,该系统
  • 自动监控核心 Web 指标
  • 在分支之间运行 A/B 测试
  • 阻止降低性能的部署
  • 提供可操作的优化建议

发现 Netlify 隐藏的性能瑰宝

许多开发人员不知道 Netlify 提供的功能

边缘函数

Netlify 边缘函数
  • 在边缘运行代码,更靠近用户
  • 实时转换响应
  • 在边缘级别进行 A/B 测试
  • 无需客户端 JS 即可个性化内容

Netlify Graph

Netlify Graph
  • 统一的 GraphQL 网关,适用于所有 API
  • 自动 TypeScript 生成
  • 内置身份验证处理
  • 无需客户端 API 密钥

按需构建器

按需构建器
  • 仅在请求时生成页面
  • 缓存动态生成的内容
  • 适用于大型网站(1 万+ 页面)
  • 显著减少构建时间

Netlify 函数

后台函数
  • 运行任务长达 15 分钟
  • 异步处理 webhook
  • 处理繁重计算
  • 无需担心超时
# Try these advanced features in cn TUI mode:
"Show me how to use Netlify Edge Functions for geo-based personalization"
"Set up On-Demand Builders for my blog with 5000 posts"
"Configure Background Functions for image processing"

性能最佳实践

Netlify 性能规则强制执行

构建优化

  • 启用依赖缓存
  • 尽可能并行构建
  • 增量编译
  • 智能缓存失效

运行时性能

  • 自动图像优化
  • 高效资源提示(预加载、预取)
  • 最佳缓存头
  • CDN 配置

监控标准

  • 强制执行性能预算
  • 核心 Web 指标跟踪
  • 真实用户监控
  • 自动化警报

高级性能策略

渐进增强

# In cn TUI mode:
"Implement progressive enhancement with basic HTML first"

多变体测试

# In cn TUI mode:
"Test 3 bundle strategies and auto-select winner"

预测预取

# In cn TUI mode:
"Analyze navigation patterns and prefetch next pages"

后续步骤

资源