Netlify 是一个用于部署和托管网站的现代 Web 开发平台。本技能围绕将应用部署到 Netlify 展开,涉及函数、表单、重定向和边缘函数等能力,适用于部署静态站点、JAMstack 应用等场景。
快速开始 安装 CLI:npm install -g netlify-cli 登录:netlify login 部署:netlify deploy 部署到生产环境:netlify deploy --prod
项目设置 可通过 Git 仓库连接:访问 app.netlify.com,选择 Add new site > Import from Git,选择仓库,配置构建设置后部署。也可使用拖拽方式:访问 https://app.netlify.com/drop 并拖入构建文件夹。
netlify.toml 配置 可配置构建命令、发布目录、函数目录、构建环境变量(如 NODE_VERSION)、生产/预览/分支等上下文命令、开发设置、响应头以及重定向规则。示例中展示了 [build]、[build.environment]、[context.production]、[context.deploy-preview]、[context.staging]、[dev]、[[headers]]、[[redirects]] 等配置段。
环境变量 可通过仪表盘设置(Site settings > Environment variables > Add variable),或通过 CLI:netlify env:set MY_VAR "value"、netlify env:list、netlify env:get MY_VAR、netlify env:unset MY_VAR。支持按上下文设置变量,如 [context.production.environment]、[context.deploy-preview.environment]、[context.branch-deploy.environment]。在构建过程中可通过 process.env.API_URL 使用,在函数中可通过 process.env.API_SECRET 使用。
无服务器函数 基础函数示例位于 netlify/functions/hello.js,返回 statusCode 与 body。TypeScript 函数示例位于 netlify/functions/users.ts,使用 @netlify/functions 的 Handler、HandlerEvent、HandlerContext 类型,根据 httpMethod 处理 GET/POST 并返回相应状态码。定时函数使用 @netlify/functions 的 schedule,示例为每天午夜运行('0 0 * * *')。后台函数以 -background 为后缀,用于异步处理,最长可运行 15 分钟。
边缘函数 基础边缘函数示例位于 netlify/edge-functions/geo.ts,使用 @netlify/edge-functions 的 Context,读取 context.geo.country?.code 与 context.geo.city 并返回 JSON 响应,通过 config 指定 path 为 /api/geo。中间件模式示例位于 netlify/edge-functions/auth.ts,检查 Authorization 头,验证 token,失败返回 401 或 403,成功则调用 context.next() 继续到源站,config 指定 path 为 /api/*。边缘函数可在 netlify.toml 中通过 [[edge_functions]] 声明 path 与 function。
重定向与重写 可使用 _redirects 文件:简单重定向(/old-page /new-page 301)、通配符重定向(/blog/* /posts/:splat 301)、重写代理(/api/* /.netlify/functions/:splat 200)、SPA 回退(/* /index.html 200)、条件重定向(如 /country/* /us/:splat 200 Country=us)。也可在 netlify.toml 中使用 [[redirects]] 配置 from、to、status、force、conditions 等。
表单 HTML 表单需设置 name、method="POST"、data-netlify="true",并包含隐藏的 form-name 输入。React 表单示例展示了通过 fetch 提交 FormData 并处理成功/失败状态。表单通知可在仪表盘配置:Forms > [Form Name] > Settings > Notifications。
身份认证(Identity) 可在 HTML 中引入 https://identity.netlify.com/v1/netlify-identity-widget.js。JavaScript API 示例使用 netlify-identity-widget,调用 init()、open(),监听 login/logout 事件,并通过 currentUser() 获取当前用户。
大文件媒体(Git LFS) 安装:netlify lm:install;设置:netlify lm:setup;跟踪文件:git lfs track ".jpg" ".png" "*.gif"。
Blobs(存储) 函数示例位于 netlify/functions/upload.ts,使用 @netlify/blobs 的 getStore('uploads'),可执行 store.set(带 metadata)、store.get、store.delete。
本地开发 启动开发服务器:netlify dev;指定端口:netlify dev --port 3000;链接站点:netlify link;拉取环境变量:netlify env:pull。
最佳实践 使用 netlify.toml 对配置进行版本控制;设置分支部署以便在生产前预览;使用上下文特定变量为不同环境设置不同值;启用表单垃圾过滤;对低延迟操作使用边缘函数。
常见错误与修复 缺少 form-name 输入:添加带表单名称的隐藏输入;发布目录错误:检查框架输出文件夹;找不到函数:使用 netlify/functions 目录;重定向不生效:检查顺序(首个匹配生效);构建失败:检查构建日志与 Node 版本。
参考文件 references/functions.md(函数模式)、references/forms.md(表单处理)、references/edge.md(边缘函数)。