mcpField
N
netlify

netlify

github.com/bobmatnyc云与 DevOps78177 次安装15 周前更新
代码仓库

关于 netlify

Netlify 技能为开发者提供 JAMstack 网站部署与平台配置参考,涵盖静态站点、无服务器函数、表单和身份管理。内容也介绍部署预览、边缘函数及通过 netlify.toml 配置构建和重定向。

主要功能

  1. 01静态站点部署与 Git 集成
  2. 02无服务器函数和边缘函数
  3. 03内置表单与身份管理
  4. 04部署预览和回滚
  5. 05netlify.toml 配置构建与重定向
  6. 06环境变量管理

适用场景

  1. 01部署静态站点和单页应用
  2. 02为 JAMstack 应用添加后端逻辑
  3. 03配置拉取请求部署预览
  4. 04管理站点环境变量与重定向

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill netlify

安装后在 Claude Code 中输入/netlify确认已加载。

附带文件metadata.json

详细介绍

Netlify 平台技能


progressive_disclosure: entry_point: summary: "JAMstack 部署平台,提供无服务器函数、表单和身份管理" when_to_use: - "部署静态网站和 SPA 时" - "构建 JAMstack 应用时" - "需要无服务器函数时" - "需要内置表单和身份验证时" quick_start: - "npm install -g netlify-cli" - "netlify login" - "netlify init" - "netlify deploy --prod" token_estimate: entry: 70-85 full: 3800-4800

Netlify 基础知识

核心概念
  • 站点:部署到 Netlify 全球 CDN 的静态网站
  • 构建:由 Git 提交触发的自动化构建流程
  • 部署上下文:production、deploy-preview、branch-deploy
  • 原子部署:全有或全无的部署,支持即时回滚
  • 即时缓存失效:自动清除 CDN 缓存
平台优势
  • 全球 CDN:内置内容分发网络
  • 持续部署:从 Git 自动部署
  • 默认启用 HTTPS:免费 SSL 证书
  • 部署预览:预览每个拉取请求
  • 无服务器函数:无需服务器即可实现后端逻辑
  • 表单和身份管理:满足常见需求的内置功能

静态网站部署

支持的框架
# React (Create React App, Vite)
Build command: npm run build
Publish directory: build (CRA) or dist (Vite)

# Next.js (Static Export)
Build command: npm run build && npm run export
Publish directory: out

# Vue.js
Build command: npm run build
Publish directory: dist

# Gatsby
Build command: gatsby build
Publish directory: public

# Hugo
Build command: hugo
Publish directory: public

# Svelte/SvelteKit
Build command: npm run build
Publish directory: build
手动部署
# Install Netlify CLI
npm install -g netlify-cli

# Login to Netlify
netlify login

# Initialize site
netlify init

# Deploy draft (preview URL)
netlify deploy

# Deploy to production
netlify deploy --prod

# Deploy with build
netlify deploy --build --prod

netlify.toml 配置

基本配置
# netlify.toml
[build]
  # Build command
  command = "npm run build"

  # Publish directory
  publish = "dist"

  # Functions directory
  functions = "netlify/functions"

# Production context
[context.production]
  command = "npm run build:prod"

[context.production.environment]
  NODE_ENV = "production"
  API_URL = "https://api.example.com"

# Deploy Preview context
[context.deploy-preview]
  command = "npm run build:preview"

# Branch deploys
[context.branch-deploy]
  command = "npm run build"
构建设置
[build]
  command = "npm run build"
  publish = "dist"

  # Base directory for monorepos
  base = "packages/web"

  # Ignore builds on certain changes
  ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF packages/web"

[build.environment]
  NODE_VERSION = "18"
  NPM_VERSION = "9"
  RUBY_VERSION = "3.1"
高级构建配置
[build]
  command = "npm run build"
  publish = "dist"

  # Build processing
  [build.processing]
    skip_processing = false
  [build.processing.css]
    bundle = true
    minify = true
  [build.processing.js]
    bundle = true
    minify = true
  [build.processing.images]
    compress = true

环境变量

设置变量
# Via CLI
netlify env:set API_KEY "secret-value"
netlify env:set NODE_ENV "production"

# List variables
netlify env:list

# Import from .env file
netlify env:import .env
变量作用域
# netlify.toml
[context.production.environment]
  API_URL = "https://api.production.com"
  ENABLE_ANALYTICS = "true"

[context.deploy-preview.environment]
  API_URL = "https://api.staging.com"
  ENABLE_ANALYTICS = "false"

[context.branch-deploy.environment]
  API_URL = "https://api.dev.com"
在构建中访问
// During build
const apiUrl = process.env.API_URL;

// Client-side (must be prefixed)
const publicKey = process.env.REACT_APP_PUBLIC_KEY;

无服务器函数

函数结构
// netlify/functions/hello.js
exports.handler = async (event, context) => {
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Hello from Netlify Function',
      path: event.path,
      method: event.httpMethod,
    }),
  };
};
TypeScript 函数
// netlify/functions/api.ts
import { Handler, HandlerEvent, HandlerContext } from '@netlify/functions';

interface RequestBody {
  name: string;
  email: string;
}

export const handler: Handler = async (
  event: HandlerEvent,
  context: HandlerContext
) => {
  if (event.httpMethod !== 'POST') {
    return {
      statusCode: 405,
      body: 'Method Not Allowed',
    };
  }

  const { name, email }: RequestBody = JSON.parse(event.body || '{}');

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: `Hello ${name}`,
      email,
    }),
  };
};
高级函数模式
// netlify/functions/database.js
const { MongoClient } = require('mongodb');

let cachedDb = null;

async function connectToDatabase() {
  if (cachedDb) return cachedDb;

  const client = await MongoClient.connect(process.env.MONGODB_URI);
  cachedDb = client.db();
  return cachedDb;
}

exports.handler = async (event) => {
  const db = await connectToDatabase();
  const users = await db.collection('users').find({}).toArray();

  return {
    statusCode: 200,
    body: JSON.stringify(users),
  };
};
定时函数
// netlify/functions/scheduled.js
const { schedule } = require('@netlify/functions');

const handler = async () => {
  console.log('Running scheduled task');

  // Your scheduled logic
  await performBackup();

  return {
    statusCode: 200,
  };
};

// Run every day at midnight
exports.handler = schedule('0 0 * * *', handler);
后台函数
// netlify/functions/background-task.js
// Auto-runs in background if response is 200 within 10s
exports.handler = async (event) => {
  // Long-running task
  await processLargeDataset();

  return {
    statusCode: 200,
  };
};

// Invoke: POST to /.netlify/functions/background-task

Netlify 表单

HTML 表单

<form name="contact" method="POST" data-netlify="true">
  <input type="hidden" name="form-name" value="contact" />

  <label>Name: <input type="text" name="name" required /></label>
  <label>Email: <input type="email" name="email" required /></label>
  <label>Message: <textarea name="message" required></textarea></label>

  <button type="submit">Send</button>
</form>
React 表单
// ContactForm.jsx
import { useState } from 'react';

export default function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: '',
  });

  const handleSubmit = async (e) => {
    e.preventDefault();

    const response = await fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        'form-name': 'contact',
        ...formData,
      }).toString(),
    });

    if (response.ok) {
      alert('Thank you for your message!');
    }
  };

  return (
    <form name="contact" onSubmit={handleSubmit} data-netlify="true">
      <input type="hidden" name="form-name" value="contact" />
      {/* Form fields */}
    </form>
  );
}
表单功能

<form name="contact" method="POST" data-netlify="true" data-netlify-honeypot="bot-field">
  <input type="hidden" name="form-name" value="contact" />
  <p class="hidden">
    <label>Don't fill this out: <input name="bot-field" /></label>
  </p>
  
</form>


<form name="contact" method="POST" data-netlify="true" data-netlify-recaptcha="true">
  <div data-netlify-recaptcha="true"></div>
  <button type="submit">Submit</button>
</form>


<form name="file-upload" method="POST" data-netlify="true" enctype="multipart/form-data">
  <input type="file" name="file" />
  <button type="submit">Upload</button>
</form>
表单通知
# netlify.toml
[[plugins]]
  package = "@netlify/plugin-emails"

  [plugins.inputs]
    formName = "contact"
    to = "[email protected]"
    subject = "New contact form submission"

Netlify Identity

启用 Identity
// Add to HTML
<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>

// Initialize
if (window.netlifyIdentity) {
  window.netlifyIdentity.on('init', user => {
    if (!user) {
      window.netlifyIdentity.on('login', () => {
        document.location.href = '/admin/';
      });
    }
  });
}
React 集成
// useNetlifyIdentity.js
import { useEffect, useState } from 'react';

export function useNetlifyIdentity() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const netlifyIdentity = window.netlifyIdentity;

    netlifyIdentity.on('init', user => setUser(user));
    netlifyIdentity.on('login', user => setUser(user));
    netlifyIdentity.on('logout', () => setUser(null));

    netlifyIdentity.init();
  }, []);

  return {
    user,
    login: () => window.netlifyIdentity.open('login'),
    logout: () => window.netlifyIdentity.logout(),
    signup: () => window.netlifyIdentity.open('signup'),
  };
}
受保护的函数
// netlify/functions/protected.js
exports.handler = async (event, context) => {
  const { user } = context.clientContext;

  if (!user) {
    return {
      statusCode: 401,
      body: 'Unauthorized',
    };
  }

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Protected data',
      user: user.email,
    }),
  };
};

重定向和重写

_redirects 文件
# _redirects file in publish directory

# Redirect with status code
/old-path  /new-path  301

# Rewrite (proxy)
/api/*  https://api.example.com/:splat  200

# SPA fallback
/*  /index.html  200

# Force HTTPS
http://example.com/*  https://example.com/:splat  301!

# Conditional redirects
/news/*  /blog/:splat  302  Country=us

# Role-based redirects
/admin/*  /admin/dashboard  200!  Role=admin
/admin/*  /unauthorized  401
netlify.toml 重定向
[[redirects]]
  from = "/old-path"
  to = "/new-path"
  status = 301

[[redirects]]
  from = "/api/*"
  to = "https://api.example.com/:splat"
  status = 200
  force = true

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

[[redirects]]
  from = "/admin/*"
  to = "/admin/dashboard"
  status = 200
  conditions = {Role = ["admin"]}

# Proxy with headers
[[redirects]]
  from = "/proxy/*"
  to = "https://backend.com/:splat"
  status = 200
  force = true
  [redirects.headers]
    X-From = "Netlify"
自定义标头
[[headers]]
  for = "/*"
  [headers.values]
    X-Frame-Options = "DENY"
    X-XSS-Protection = "1; mode=block"
    Content-Security-Policy = "default-src 'self'"

[[headers]]
  for = "/assets/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

部署预览

自动预览 URL
# netlify.toml
[context.deploy-preview]
  command = "npm run build:preview"

[context.deploy-preview.environment]
  NODE_ENV = "preview"
  API_URL = "https://api-staging.example.com"
分支部署
# Deploy specific branches
[context.staging]
  command = "npm run build:staging"

[context.staging.environment]
  API_URL = "https://api-staging.example.com"

# Branch pattern matching
[context.branch-deploy]
  command = "npm run build"
部署通知
# GitHub PR comments
# Slack notifications
# Email notifications
# Configured in Netlify UI

分流测试(A/B 测试)

配置
# netlify.toml
[[redirects]]
  from = "/*"
  to = "/version-a/:splat"
  status = 200
  conditions = {Cookie = ["ab_test=a"]}
  force = true

[[redirects]]
  from = "/*"
  to = "/version-b/:splat"
  status = 200
  conditions = {Cookie = ["ab_test=b"]}
  force = true

# 50/50 split
[[redirects]]
  from = "/*"
  to = "/version-a/:splat"
  status = 200!
  percentage = 50

[[redirects]]
  from = "/*"
  to = "/version-b/:splat"
  status = 200!

Edge Functions

Deno 运行时
// netlify/edge-functions/hello.ts
import type { Context } from "https://edge.netlify.com";

export default async (request: Request, context: Context) => {
  const url = new URL(request.url);

  return new Response(`Hello from ${url.pathname}`, {
    headers: { "content-type": "text/html" },
  });
};

export const config = { path: "/hello" };
地理位置
// netlify/edge-functions/geo.ts
import type { Context } from "https://edge.netlify.com";

export default async (request: Request, context: Context) => {
  const { city, country } = context.geo;

  return Response.json({
    location: `${city}, ${country}`,
  });
};
转换响应
// netlify/edge-functions/transform.ts
import type { Context } from "https://edge.netlify.com";

export default async (request: Request, context: Context) => {
  const response = await context.next();
  const text = await response.text();

  // Modify HTML
  const modified = text.replace(
    '</body>',
    '<script>console.log("Injected by edge");</script></body>'
  );

  return new Response(modified, response);
};

export const config = { path: "/*" };

自定义域名和 SSL

添加自定义域名
# Via CLI
netlify domains:add example.com

# DNS Configuration
# A record: 75.2.60.5
# CNAME: <site-name>.netlify.app

# Verify domain
netlify domains:verify example.com
SSL 证书
# Automatic HTTPS (default)
# Free Let's Encrypt certificates
# Auto-renewal

# Force HTTPS redirect
[[redirects]]
  from = "http://example.com/*"
  to = "https://example.com/:splat"
  status = 301
  force = true

分析

Netlify Analytics


自定义分析
// Track custom events
function trackEvent(eventName, data) {
  fetch('/.netlify/functions/analytics', {
    method: 'POST',
    body: JSON.stringify({ event: eventName, ...data }),
  });
}

trackEvent('button_click', { button: 'signup' });

CLI 高级用法

开发服务器
# Run functions locally
netlify dev

# Specific port
netlify dev --port 3000

# Live session sharing
netlify dev --live

# Functions only
netlify functions:serve
站点管理
# Link existing site
netlify link

# Create new site
netlify sites:create

# List sites
netlify sites:list

# Site info
netlify status

# Open site in browser
netlify open
部署管理
# List deploys
netlify deploy:list

# Rollback to previous deploy
netlify rollback

# Cancel deploy
netlify deploy:cancel <deploy-id>

Git 集成

持续部署
# netlify.toml
[build]
  command = "npm run build"
  publish = "dist"

# Auto-publish on Git push
# Production: main/master branch
# Previews: all pull requests
# Branch deploys: configured branches
部署钩子
# Trigger builds via webhook
curl -X POST -d {} https://api.netlify.com/build_hooks/<hook-id>

# Scheduled builds (use external cron + webhook)

最佳实践

性能优化
# Enable processing
[build.processing]
  skip_processing = false

[build.processing.css]
  bundle = true
  minify = true

[build.processing.js]
  bundle = true
  minify = true

[build.processing.images]
  compress = true

# Asset optimization
[[headers]]
  for = "/assets/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"
安全标头
[[headers]]
  for = "/*"
  [headers.values]
    X-Frame-Options = "DENY"
    X-Content-Type-Options = "nosniff"
    X-XSS-Protection = "1; mode=block"
    Referrer-Policy = "strict-origin-when-cross-origin"
    Permissions-Policy = "geolocation=(), microphone=(), camera=()"
    Content-Security-Policy = """
      default-src 'self';
      script-src 'self' 'unsafe-inline';
      style-src 'self' 'unsafe-inline';
      img-src 'self' data: https:;
      font-src 'self' data:;
    """
函数最佳实践
// Keep functions lightweight
// Use connection pooling
// Cache external API responses
// Set appropriate timeouts
// Handle errors gracefully

exports.handler = async (event) => {
  try {
    // Set timeout
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 8000);

    const response = await fetch(API_URL, {
      signal: controller.signal,
    });

    clearTimeout(timeout);

    return {
      statusCode: 200,
      body: JSON.stringify(await response.json()),
    };
  } catch (error) {
    console.error('Function error:', error);

    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Internal server error' }),
    };
  }
};
构建优化
[build]
  command = "npm run build"
  publish = "dist"

  # Skip builds when not needed
  ignore = """
    git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF -- . ':(exclude)docs/' ':(exclude)*.md'
  """

# Cache dependencies
[build.environment]
  NPM_FLAGS = "--legacy-peer-deps"
  NODE_OPTIONS = "--max-old-space-size=4096"
Monorepo 支持
# netlify.toml
[build]
  base = "packages/web"
  command = "npm run build"
  publish = "dist"

  # Only build when package changes
  ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF packages/web"

常见模式

带 API 代理的 SPA
[build]
  command = "npm run build"
  publish = "build"
  functions = "netlify/functions"

[[redirects]]
  from = "/api/*"
  to = "/.netlify/functions/:splat"
  status = 200

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200
使用子文件夹的微型站点
[[redirects]]
  from = "/blog/*"
  to = "https://blog.example.com/:splat"
  status = 200
  force = true
身份验证网关
[[redirects]]
  from = "/app/*"
  to = "/app/dashboard"
  status = 200
  conditions = {Role = ["user"]}

[[redirects]]
  from = "/app/*"
  to = "/login"
  status = 302

总结:Netlify 提供完整的 JAMstack 平台,包含静态托管、无服务器函数、表单和身份管理。其主要优势包括原子部署、即时缓存失效、部署预览和内置 CDN。通过 netlify.toml 配置构建、重定向、标头和特定环境的设置。利用无服务器函数实现后端逻辑,使用表单收集用户输入,并借助 Edge Functions 执行边缘计算。最佳实践包括性能优化、安全标头和高效的构建配置。

评论

支持 Markdown