Claude Code + Figma MCP 入门教程:从设计稿到代码的智能桥梁
🎯 引言
想象一下这样的工作场景:设计师在 Figma 中完成了精美的 UI 设计,你打开 Claude Code,输入一句话,几秒钟后,规范的 React 组件代码、完整的样式定义就自动生成了。这不是科幻,而是 Claude Code + Figma MCP 能为你实现的真实工作流。
这个组合能帮你做什么?
✅ 自动提取设计规范:颜色、字体、间距一键导出✅ 智能生成组件代码:从设计稿直接生成 React/Vue 组件✅ 保持设计一致性:设计变更自动同步到代码✅ 节省 60% 的 UI 开发时间:告别手动测量和样式调试
本文目标
无论你是前端新手还是资深开发者,读完这篇教程你将学会:
- 理解 MCP 的工作原理
- 配置两种 Figma MCP 方案(官方 & 非官方)
- 用实际案例掌握从设计稿到代码的完整流程
📚 基础知识铺垫
什么是 MCP (Model Context Protocol)?
把 MCP 理解为 AI 的 "USB 接口":
- 传统 USB 让电脑连接各种设备(鼠标、键盘、打印机)
- MCP 让 AI 连接各种工具(Figma、GitHub、数据库)
通俗解释:MCP 是一套标准协议,让 Claude 可以安全地访问外部服务,就像给 AI 装上了 "手" 和 "眼睛"。
Claude Code 是什么?
| 对比项 | 普通 Claude | Claude Code |
|---|---|---|
| 定位 | 通用对话助手 | 专为开发者设计 |
| 代码能力 | 基础 | 深度优化(支持项目级理解) |
| MCP 支持 | ❌ | ✅ 可连接开发工具 |
| 使用场景 | 写文案、答疑 | 写代码、调试、自动化 |
Figma 在前端开发中的作用
Figma 是设计师的画布,但对开发者来说:
- 🎨 设计资产库:存储颜色、字体、组件规范
- 📐 精确测量工具:获取尺寸、间距、圆角等参数
- 🔗 协作枢纽:设计师和开发者的沟通桥梁
为什么需要连接 Figma 和 Claude?
传统流程的痛点:
设计师交付设计稿
↓
开发者手动测量尺寸
↓
逐个编写 CSS 样式
↓
反复对比调整
↓
耗时 3-5 小时
MCP 加持后:
设计稿链接发给 Claude
↓
AI 自动读取设计参数
↓
生成规范代码
↓
开发者微调优化
↓
耗时 30 分钟
📊 两种方案对比
| 特性 | 官方 MCP | 非官方 MCP (figma-developer-mcp) |
|---|---|---|
| 免费额度 | 前 10 次免费 | 完全取决于 Figma API 限制 |
| 配置难度 | ⭐ 一键安装 | ⭐⭐⭐ 需配置 API Key |
| 功能范围 | 基础读取 | 支持更多高级操作 |
| 稳定性 | 官方维护 | 社区维护 |
| 适用场景 | 快速体验 / 轻度使用 | 频繁使用 / 生产环境 |
| 安全性 | OAuth 授权 | 需妥善保管 API Key |
💡 选择建议:
- 刚开始学习?→ 先用官方 MCP 体验
- 需要频繁使用?→ 配置非官方 MCP
- 企业项目?→ 非官方 MCP + 团队 API Key 管理
🛠️ 准备工作
必备清单
1. Claude Code 账号
- 访问
- 选择 Pro 订阅(支持 MCP 功能)
- 💰 费用:$20 / 月
2. Figma 账号
- 访问
- 免费版即可(Starter 计划)
- 确保有至少一个设计文件用于测试
3. 开发环境(仅非官方方案需要)
- Node.js 18+
- 任意代码编辑器(推荐 VS Code)
4. 测试用设计稿
如果没有现成的,可以使用这个公开模板:
- (搜索 "Button Component")
🚀 方案一:官方 MCP 配置(5 分钟上手)
步骤 1:启用 Figma MCP
- 打开 Claude Code 界面
- 点击右下角 "⚙️ Settings"
- 选择 "Integrations" 标签
- 在 MCP 商店中找到 "Figma"
┌─────────────────────────────────┐
│ MCP Integration Store │
├─────────────────────────────────┤
│ 🎨 Figma │
│ Connect to Figma designs │
│ [Install] ← 点击这里 │
└─────────────────────────────────┘
步骤 2:授权 Figma 访问
点击安装后会弹出授权窗口:
┌──────────────────────────────────┐
│ Figma Authorization │
├──────────────────────────────────┤
│ Claude Code 请求以下权限: │
│ ✓ 读取你的 Figma 文件 │
│ ✓ 查看设计组件 │
│ │
│ [ Allow Access ] [ Cancel ] │
└──────────────────────────────────┘
⚠️ 注意:仅授予读取权限,Claude 无法修改你的设计稿
步骤 3:测试连接
在 Claude Code 对话框中输入:
请列出我 Figma 账户中的所有文件
预期返回:
我找到了以下 Figma 文件:
1. 📱 Mobile App Redesign
- 最后修改:2 天前
- 文件 ID: abc123xyz
2. 🌐 Website Components
- 最后修改:1 周前
- 文件 ID: def456uvw
你想查看哪个文件的详细信息?
✅ 看到类似输出说明配置成功!
步骤 4:基础使用案例
案例 A:提取颜色规范
提示词:
从文件"Website Components"中提取所有颜色,
生成 CSS 变量格式
AI 返回:
:root {
/* Primary Colors */
--color-primary-500: #3B82F6;
--color-primary-600: #2563EB;
/* Neutral Colors */
--color-gray-50: #F9FAFB;
--color-gray-900: #111827;
/* Semantic Colors */
--color-success: #10B981;
--color-error: #EF4444;
}
案例 B:生成按钮组件
提示词:
查看"Website Components"中的主按钮设计,
生成 React + Tailwind CSS 代码
AI 返回:
interface ButtonProps {
children: React.ReactNode;
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
}
export const Button: React.FC<ButtonProps> = ({
children,
variant = 'primary',
size = 'md'
}) => {
const baseClasses = 'rounded-lg font-semibold transition-colors';
const variantClasses = {
primary: 'bg-blue-600 hover:bg-blue-700 text-white',
secondary: 'bg-gray-200 hover:bg-gray-300 text-gray-900'
};
const sizeClasses = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-base',
lg: 'px-6 py-3 text-lg'
};
return (
<button
className={`
${baseClasses}
${variantClasses[variant]}
${sizeClasses[size]}
`}
>
{children}
</button>
);
};
🔧 方案二:非官方 MCP 配置(高级用法)
步骤 1:获取 Figma API Key
详细指引:
- 登录 Figma 网页版
- 点击右上角头像 → Settings
- 滚动到 "Personal Access Tokens" 部分
- 点击 "Generate new token"
┌────────────────────────────────────┐
│ Personal Access Tokens │
├────────────────────────────────────┤
│ Token description: │
│ [Claude MCP Integration] │
│ │
│ Expiration: [Never] ▼ │
│ Scopes: │
│ ☑ File content - Read only │
│ │
│ [Generate Token] │
└────────────────────────────────────┘
- 复制生成的 Token(只会显示一次!)
- 格式类似:
figd_Xy8h2kL9mN4pQ7rS...
- 格式类似:
⚠️ 安全警告:
- 像密码一样保管这个 Token
- 不要提交到 Git 仓库
- 建议使用环境变量存储
步骤 2:安装非官方 MCP 服务器
打开终端,执行:
# 使用 npx 直接运行(推荐)
npx -y @modelcontextprotocol/server-figma
# 或全局安装
npm install -g @modelcontextprotocol/server-figma
步骤 3:配置文件设置
macOS/Linux 配置路径:
~/.config/claude/mcp-settings.json
Windows 配置路径:
%APPDATA%\Claude\mcp-settings.json
配置文件内容:
json
{
"mcpServers": {
"figma": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-figma"
],
"env": {
"FIGMA_PERSONAL_ACCESS_TOKEN": "你的_API_Key"
}
}
}
}
💡 进阶技巧:使用环境变量
json
{
"mcpServers": {
"figma": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-figma"],
"env": {
"FIGMA_PERSONAL_ACCESS_TOKEN": "${FIGMA_TOKEN}"
}
}
}
}
然后在系统环境变量中设置 FIGMA_TOKEN。
步骤 4:在 Claude Code 中连接
- 重启 Claude Code 应用
- 在对话中输入:
列出可用的 MCP 工具
预期返回:
当前已连接的 MCP 服务器:
✅ figma
- get_file: 获取 Figma 文件内容
- get_comments: 读取设计评论
- get_components: 获取组件库
所有服务运行正常!
步骤 5:高级功能测试
获取文件 ID
在 Figma 中打开设计稿,URL 格式为:
https://www.figma.com/file/ABC123/Design-Name
^^^^^^
这是文件 ID
深度读取设计
提示词:
使用 MCP 工具获取文件 ABC123 的完整结构,
包括所有图层和样式定义
AI 会调用:
// Claude 内部调用的 MCP 命令
mcp.figma.get_file({
file_id: "ABC123",
depth: "full"
})
🎨 实战案例:从 Figma 到代码
案例 1:提取完整设计系统
场景
你的团队设计师在 Figma 中建立了设计系统,包含颜色、排版、间距规范。
提示词模板
分析 Figma 文件 [文件ID],提取以下设计 Token:
1. 颜色系统
- 主色调(Primary)
- 中性色(Neutral)
- 语义色(Success/Warning/Error)
2. 排版系统
- 字体家族
- 字号层级
- 行高规范
3. 间距系统
- 基础单位
- 间距比例
输出格式:
- CSS 变量(:root)
- Tailwind 配置
- JavaScript Token 对象
AI 生成结果
1. CSS 变量
:root {
/* Colors */
--primary-50: #EFF6FF;
--primary-500: #3B82F6;
--primary-900: #1E3A8A;
/* Typography */
--font-sans: 'Inter', system-ui, sans-serif;
--text-xs: 0.75rem; /* 12px */
--text-sm: 0.875rem; /* 14px */
--text-base: 1rem; /* 16px */
--text-lg: 1.125rem; /* 18px */
/* Spacing */
--space-unit: 0.25rem; /* 4px */
--space-1: 0.25rem; /* 4px */
--space-2: 0.5rem; /* 8px */
--space-4: 1rem; /* 16px */
--space-6: 1.5rem; /* 24px */
}
2. Tailwind 配置
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: {
50: '#EFF6FF',
500: '#3B82F6',
900: '#1E3A8A',
}
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
},
fontSize: {
'xs': '0.75rem',
'sm': '0.875rem',
'base': '1rem',
'lg': '1.125rem',
},
spacing: {
'1': '0.25rem',
'2': '0.5rem',
'4': '1rem',
'6': '1.5rem',
}
}
}
}
3. JavaScript Token
// design-tokens.ts
export const tokens = {
colors: {
primary: {
50: '#EFF6FF',
500: '#3B82F6',
900: '#1E3A8A',
}
},
typography: {
fontFamily: {
sans: 'Inter, system-ui, sans-serif'
},
fontSize: {
xs: '12px',
sm: '14px',
base: '16px',
lg: '18px',
}
},
spacing: {
unit: 4,
scale: [4, 8, 16, 24, 32, 48, 64]
}
} as const;
案例 2:智能生成卡片组件
场景
设计稿中有一个产品卡片,包含图片、标题、描述、价格和按钮。
提示词
查看 Figma 文件 [文件ID] 中名为 "Product Card" 的组件。
生成要求:
1. 使用 React + TypeScript
2. 样式采用 Tailwind CSS
3. 支持以下 Props:
- image(图片 URL)
- title(标题)
- description(描述)
- price(价格)
- onPurchase(点击回调)
4. 添加 hover 动画效果
5. 响应式设计(移动端适配)
AI 生成代码
// ProductCard.tsx
import React from 'react';
interface ProductCardProps {
image: string;
title: string;
description: string;
price: number;
onPurchase: () => void;
}
export const ProductCard: React.FC<ProductCardProps> = ({
image,
title,
description,
price,
onPurchase
}) => {
return (
<div className="
group
bg-white
rounded-2xl
shadow-md
overflow-hidden
transition-all
duration-300
hover:shadow-xl
hover:-translate-y-1
max-w-sm
">
{/* 图片容器 */}
<div className="relative aspect-square overflow-hidden">
<img
src={image}
alt={title}
className="
w-full
h-full
object-cover
transition-transform
duration-500
group-hover:scale-110
"
/>
</div>
{/* 内容区域 */}
<div className="p-6 space-y-4">
<h3 className="
text-xl
font-semibold
text-gray-900
line-clamp-2
">
{title}
</h3>
<p className="
text-sm
text-gray-600
line-clamp-3
">
{description}
</p>
{/* 价格和按钮 */}
<div className="
flex
items-center
justify-between
pt-4
border-t
border-gray-100
">
<span className="
text-2xl
font-bold
text-blue-600
">
${price.toFixed(2)}
</span>
<button
onClick={onPurchase}
className="
px-6
py-2.5
bg-blue-600
hover:bg-blue-700
text-white
font-medium
rounded-lg
transition-colors
active:scale-95
"
>
Add to Cart
</button>
</div>
</div>
</div>
);
};
// 使用示例
export default function Example() {
return (
<ProductCard
image="https://example.com/product.jpg"
title="Wireless Headphones"
description="Premium sound quality with active noise cancellation"
price={299.99}
onPurchase={() => console.log('购买')}
/>
);
}
移动端适配版本
// 添加响应式断点
<div className="
bg-white
rounded-2xl
shadow-md
overflow-hidden
transition-all
duration-300
hover:shadow-xl
max-w-sm
sm:max-w-md /* 平板 */
lg:max-w-lg /* 桌面 */
">
{/* 移动端时图片比例调整 */}
<div className="
relative
aspect-square /* 默认 1:1 */
sm:aspect-video /* 平板改为 16:9 */
">
{/* ... */}
</div>
</div>
案例 3:整页面转换
场景
设计师交付了一个登录页面,包含表单、背景、品牌元素。
提示词
分析 Figma 页面 "Login Page",生成完整的 HTML/CSS 实现。
要求:
1. 语义化 HTML5 标签
2. CSS Grid + Flexbox 布局
3. 表单验证(前端)
4. 响应式设计(支持手机到 4K 显示器)
5. 无障碍访问(ARIA 标签)
6. 深色模式支持
输出文件:
- index.html
- styles.css
- script.js(表单验证逻辑)
AI 生成的完整代码
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 我的应用</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main class="login-container">
<!-- 左侧品牌区域 -->
<section class="brand-section" aria-label="品牌介绍">
<div class="brand-content">
<img src="logo.svg" alt="公司标志" class="logo">
<h1>欢迎回来</h1>
<p>连接世界,从这里开始</p>
</div>
</section>
<!-- 右侧表单区域 -->
<section class="form-section">
<form id="loginForm" class="login-form" novalidate>
<h2>登录账户</h2>
<!-- 邮箱输入 -->
<div class="form-group">
<label for="email">邮箱地址</label>
<input
type="email"
id="email"
name="email"
placeholder="your@email.com"
required
aria-required="true"
aria-describedby="email-error"
>
<span id="email-error" class="error-message" role="alert"></span>
</div>
<!-- 密码输入 -->
<div class="form-group">
<label for="password">密码</label>
<input
type="password"
id="password"
name="password"
placeholder="••••••••"
required
aria-required="true"
aria-describedby="password-error"
>
<span id="password-error" class="error-message" role="alert"></span>
</div>
<!-- 记住我 & 忘记密码 -->
<div class="form-options">
<label class="checkbox-label">
<input type="checkbox" name="remember">
<span>记住我</span>
</label>
<a href="/forgot-password" class="link">忘记密码?</a>
</div>
<!-- 提交按钮 -->
<button type="submit" class="submit-button">
登录
</button>
<!-- 注册链接 -->
<p class="signup-prompt">
还没有账户?<a href="/signup" class="link">立即注册</a>
</p>
</form>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
styles.css
/* ========== CSS 变量(支持深色模式)========== */
:root {
--color-primary: #3B82F6;
--color-primary-dark: #2563EB;
--color-background: #FFFFFF;
--color-surface: #F9FAFB;
--color-text: #111827;
--color-text-secondary: #6B7280;
--color-border: #E5E7EB;
--color-error: #EF4444;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: #111827;
--color-surface: #1F2937;
--color-text: #F9FAFB;
--color-text-secondary: #9CA3AF;
--color-border: #374151;
}
}
/* ========== 基础样式 ========== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--color-background);
color: var(--color-text);
line-height: 1.6;
}
/* ========== 布局 ========== */
.login-container {
display: grid;
grid-template-columns: 1fr 1fr;
min-height: 100vh;
}
@media (max-width: 768px) {
.login-container {
grid-template-columns: 1fr;
}
.brand-section {
display: none; /* 移动端隐藏品牌区 */
}
}
/* ========== 品牌区域 ========== */
.brand-section {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 3rem;
color: white;
}
.brand-content {
text-align: center;
max-width: 400px;
}
.logo {
width: 80px;
height: 80px;
margin-bottom: 2rem;
}
.brand-content h1 {
font-size: 2.5rem;
margin-bottom: 1rem;
font-weight: 700;
}
.brand-content p {
font-size: 1.125rem;
opacity: 0.9;
}
/* ========== 表单区域 ========== */
.form-section {
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
background-color: var(--color-surface);
}
.login-form {
width: 100%;
max-width: 400px;
}
.login-form h2 {
font-size: 1.875rem;
margin-bottom: 2rem;
color: var(--color-text);
}
/* ========== 表单组件 ========== */
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: var(--color-text);
}
.form-group input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid var(--color-border);
border-radius: 0.5rem;
font-size: 1rem;
background-color: var(--color-background);
color: var(--color-text);
transition: all 0.2s;
}
.form-group input:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.form-group input.error {
border-color: var(--color-error);
}
.error-message {
display: block;
margin-top: 0.5rem;
font-size: 0.875rem;
color: var(--color-error);
min-height: 1.25rem;
}
/* ========== 表单选项 ========== */
.form-options {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.checkbox-label {
display: flex;
align-items: center;
cursor: pointer;
font-size: 0.875rem;
}
.checkbox-label input {
margin-right: 0.5rem;
width: auto;
}
.link {
color: var(--color-primary);
text-decoration: none;
font-size: 0.875rem;
font-weight: 500;
}
.link:hover {
text-decoration: underline;
}
/* ========== 按钮 ========== */
.submit-button {
width: 100%;
padding: 0.75rem 1.5rem;
background-color: var(--color-primary);
color: white;
border: none;
border-radius: 0.5rem;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.submit-button:hover {
background-color: var(--color-primary-dark);
transform: translateY(-1px);
box-shadow: var(--shadow-md);
}
.submit-button:active {
transform: translateY(0);
}
.submit-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* ========== 注册提示 ========== */
.signup-prompt {
text-align: center;
margin-top: 1.5rem;
color: var(--color-text-secondary);
font-size: 0.875rem;
}
script.js
// 表单验证逻辑
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
// 清除之前的错误
clearErrors();
// 获取表单数据
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
let isValid = true;
// 验证邮箱
if (!validateEmail(email)) {
showError('email', '请输入有效的邮箱地址');
isValid = false;
}
// 验证密码
if (password.length < 8) {
showError('password', '密码至少需要 8 个字符');
isValid = false;
}
// 如果验证通过,提交表单
if (isValid) {
submitForm(email, password);
}
});
// 邮箱验证函数
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
// 显示错误
function showError(fieldId, message) {
const input = document.getElementById(fieldId);
const errorSpan = document.getElementById(`${fieldId}-error`);
input.classList.add('error');
errorSpan.textContent = message;
}
// 清除错误
function clearErrors() {
document.querySelectorAll('.error-message').forEach(span => {
span.textContent = '';
});
document.querySelectorAll('input').forEach(input => {
input.classList.remove('error');
});
}
// 提交表单(模拟)
async function submitForm(email, password) {
const button = document.querySelector('.submit-button');
button.disabled = true;
button.textContent = '登录中...';
try {
// 这里应该调用实际的 API
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (response.ok) {
window.location.href = '/dashboard';
} else {
showError('password', '邮箱或密码错误');
}
} catch (error) {
showError('password', '网络错误,请稍后重试');
} finally {
button.disabled = false;
button.textContent = '登录';
}
}
// 实时验证
document.getElementById('email').addEventListener('blur', function() {
if (this.value && !validateEmail(this.value)) {
showError('email', '请输入有效的邮箱地址');
}
});
💡 最佳实践建议
1. Figma 文件组织规范
✅ 好的命名规范
Components/
├── Button/Primary
├── Button/Secondary
├── Card/Product
└── Form/Input
Styles/
├── Colors/Primary/500
├── Typography/Heading/H1
└── Effects/Shadow/Medium
❌ 避免的命名
- 图层 1
- 矩形副本副本
- Group 123
- 未命名组件
为什么重要?
- Claude 会根据图层名称理解组件用途
- 清晰的命名可以生成更准确的代码注释
- 便于团队协作和代码维护
2. 设计稿准备 Checklist
在请求 AI 生成代码前,确保:
- 组件已转为 Figma Component(不是普通图层)
- 颜色使用了 Styles(而非硬编码的色值)
- 文本使用了 Text Styles(统一字体规范)
- 间距符合 8px 网格系统(便于转换为 Tailwind)
- 添加了 Auto Layout(AI 能更好理解布局意图)
3. 何时使用官方 vs 非官方 MCP
表格
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 学习阶段 | 官方 MCP | 配置简单,无需担心 API 限制 |
| 个人项目 | 官方 MCP | 每月 10 次通常够用 |
| 小团队(<5 人) | 非官方 MCP | 共享一个 API Key 即可 |
| 企业项目 | 非官方 MCP | 无频率限制,更稳定 |
| CI/CD 集成 | 非官方 MCP | 可编程调用 |
4. 提示词优化技巧
基础提示词
生成这个按钮的代码
优化后提示词
分析 Figma 中的 "Button/Primary" 组件,生成:
技术栈:React + TypeScript + Tailwind CSS
Props 设计:
- size: 'sm' | 'md' | 'lg'
- variant: 'solid' | 'outline' | 'ghost'
- isLoading: boolean
- disabled: boolean
额外要求:
1. 包含 loading 状态的 spinner 动画
2. 支持 icon + text 组合
3. 遵循 WCAG 2.1 AA 无障碍标准
4. 添加完整的 JSDoc 注释
输出文件:
- Button.tsx(组件代码)
- Button.stories.tsx(Storybook 示例)
- Button.test.tsx(单元测试)
效果对比:
- 基础提示词:生成简单的
<button>标签 - 优化提示词:生成生产级可复用组件
🔧 常见问题解决
Q1: 连接失败怎么办?
症状:提示 "Unable to connect to Figma MCP"
解决步骤:
-
检查网络连接
# 测试能否访问 Figma API curl https://api.figma.com/v1/me \ -H "X-Figma-Token: 你的_API_Key" -
验证 API Key
- 确保 Token 未过期
- 检查是否复制完整(包含
figd_前缀)
-
重启 MCP 服务
# 杀死现有进程 pkill -f "figma" # 重新启动 Claude Code -
查看日志
# macOS/Linux tail -f ~/.config/claude/mcp.log # Windows type %APPDATA%\Claude\mcp.log
Q2: API 额度用完了怎么办?
官方 MCP 限制:
- 免费:10 次 / 月
- Pro 订阅:100 次 / 月
解决方案:
方案 A:切换到非官方 MCP
Figma 官方 API 限制更宽松:
- 个人用户:2 次 / 秒
- 团队账户:无限制
方案 B:优化使用频率
❌ 低效提示词:
"帮我看看这个设计稿"
(浪费 1 次额度,返回信息少)
✅ 高效提示词:
"一次性提取文件 ABC123 的:
1. 完整颜色系统
2. 所有组件列表
3. 排版规范
并生成设计 Token 文件"
(1 次额度获取所有需要的信息)
方案 C:本地缓存设计数据
// 第一次调用时缓存结果
const designTokens = await claude.getFigmaFile('ABC123');
localStorage.setItem('design-tokens', JSON.stringify(designTokens));
// 后续使用缓存数据
const cached = JSON.parse(localStorage.getItem('design-tokens'));
Q3: 生成的代码质量不理想?
常见问题:
问题 1:样式不精确
/* AI 生成的代码 */
padding: 10px;
/* 实际设计稿 */
padding: 12px;
解决方法:在提示词中明确要求:
严格按照 Figma 中的数值生成代码,
不要四舍五入或估算。
保留小数点后 2 位。
问题 2:缺少交互逻辑
优化提示词:
除了静态样式,还需要:
1. Hover/Focus/Active 状态
2. 点击涟漪效果(Material Design)
3. 键盘导航支持(Tab/Enter)
4. 触摸设备优化(增大点击区域)
问题 3:代码不符合项目规范
提供上下文:
我们项目使用:
- CSS Modules(不是 Tailwind)
- BEM 命名规范
- Prettier 格式化配置:单引号,2 空格缩进
请按此规范生成代码。
Q4: 如何处理复杂设计稿?
场景:整个页面有 50+ 个组件
策略 1:分层提取
第一步:提取设计系统
"先分析设计稿中的基础元素:颜色、字体、间距"
第二步:生成原子组件
"生成最小组件:Button、Input、Icon"
第三步:组合分子组件
"基于原子组件,生成 Card、Form、Navigation"
第四步:构建页面
"组合所有组件,生成完整页面"
策略 2:使用 Frame 分组在 Figma 中:
Page: Homepage
├── Frame: Header
├── Frame: Hero Section
├── Frame: Features
└── Frame: Footer
提示词:
逐个分析 Homepage 页面中的 Frame:
1. 先生成 Header 组件
2. 等我确认后,再继续 Hero Section
Q5: 安全性考虑(API Key 泄露风险)
风险场景:
- 不小心提交到 Git 仓库
- 在团队聊天中分享屏幕截图
- 硬编码在前端代码中
最佳实践:
1. 使用环境变量
# .env.local(添加到 .gitignore)
FIGMA_TOKEN=figd_your_token_here
// 代码中引用
const token = process.env.FIGMA_TOKEN;
2. 定期轮换 Token
建议:每 3 个月更换一次 API Key
在 Figma Settings 中:
1. 生成新 Token
2. 更新环境变量
3. 删除旧 Token
3. 使用受限权限
生成 Token 时只授予必要权限:
- ✅ File content - Read only
- ❌ File content - Write(通常不需要)
4. 团队 API Key 管理
使用密钥管理工具:
🚀 进阶技巧
1. 结合 Design Tokens 标准
什么是 Design Tokens?
设计 Token 是设计系统的 "原子单位",将设计决策转化为代码变量。
标准格式(W3C Design Tokens)
{
"color": {
"primary": {
"$type": "color",
"$value": "#3B82F6",
"$description": "主品牌色"
}
},
"spacing": {
"base": {
"$type": "dimension",
"$value": "4px"
}
}
}
提示词模板
从 Figma 文件提取设计 Token,
输出为 W3C Design Tokens 格式(JSON)。
包含:
- colors(颜色)
- typography(排版)
- spacing(间距)
- borderRadius(圆角)
- shadows(阴影)
并生成转换脚本,支持输出为:
- CSS 变量
- SCSS 变量
- Tailwind 配置
- iOS Swift 代码
- Android XML 资源
AI 生成示例
tokens.json
{
"color": {
"brand": {
"primary": {
"$type": "color",
"$value": "#3B82F6"
},
"secondary": {
"$type": "color",
"$value": "#8B5CF6"
}
},
"semantic": {
"success": {
"$type": "color",
"$value": "#10B981"
},
"error": {
"$type": "color",
"$value": "#EF4444"
}
}
},
"spacing": {
"xs": { "$type": "dimension", "$value": "4px" },
"sm": { "$type": "dimension", "$value": "8px" },
"md": { "$type": "dimension", "$value": "16px" },
"lg": { "$type": "dimension", "$value": "24px" }
}
}
transform.js(转换脚本)
const tokens = require('./tokens.json');
// 转换为 CSS 变量
function toCSSVariables(tokens) {
let css = ':root {\n';
function traverse(obj, prefix = '') {
for (const [key, value] of Object.entries(obj)) {
if (value.$value) {
const varName = `--${prefix}${key}`.replace(/\./g, '-');
css += ` ${varName}: ${value.$value};\n`;
} else if (typeof value === 'object') {
traverse(value, `${prefix}${key}-`);
}
}
}
traverse(tokens);
css += '}';
return css;
}
// 转换为 Tailwind 配置
function toTailwindConfig(tokens) {
return {
theme: {
extend: {
colors: {
primary: tokens.color.brand.primary.$value,
secondary: tokens.color.brand.secondary.$value,
},
spacing: {
xs: tokens.spacing.xs.$value,
sm: tokens.spacing.sm.$value,
md: tokens.spacing.md.$value,
lg: tokens.spacing.lg.$value,
}
}
}
};
}
console.log(toCSSVariables(tokens));
console.log(JSON.stringify(toTailwindConfig(tokens), null, 2));
2. 自动化工作流设置
场景:设计更新自动同步代码
工具链:
- Figma Webhooks(设计文件变更通知)
- GitHub Actions(自动化脚本)
- Claude Code API(生成代码)
实现步骤
1. 配置 Figma Webhook
// webhook-handler.js
const express = require('express');
const app = express();
app.post('/figma-webhook', async (req, res) => {
const { file_key, timestamp } = req.body;
console.log(`设计文件 ${file_key} 已更新于 ${timestamp}`);
// 触发代码生成
await triggerCodeGeneration(file_key);
res.status(200).send('OK');
});
async function triggerCodeGeneration(fileKey) {
// 调用 Claude API 生成新代码
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': process.env.CLAUDE_API_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
messages: [{
role: 'user',
content: `使用 Figma MCP 分析文件 ${fileKey},
生成更新后的组件代码`
}]
})
});
const code = await response.json();
// 创建 Pull Request
await createPullRequest(code);
}
2. GitHub Actions 配置
# .github/workflows/figma-sync.yml
name: Sync Figma Changes
on:
repository_dispatch:
types: [figma-update]
jobs:
generate-code:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Generate code from Figma
env:
FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}
CLAUDE_API_KEY: ${{ secrets.CLAUDE_API_KEY }}
run: node scripts/generate-from-figma.js
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5
with:
title: '🎨 同步 Figma 设计变更'
body: |
自动生成的 PR,包含以下更新:
- 组件样式调整
- 设计 Token 更新
请 review 后合并。
branch: figma-sync-${{ github.run_number }}
3. 与版本控制集成
Git Workflow
# 1. 创建设计分支
git checkout -b design/new-button-style
# 2. 运行代码生成脚本
npm run generate-from-figma -- --component=Button
# 3. 查看差异
git diff src/components/Button.tsx
# 4. 提交变更
git add .
git commit -m "feat: 更新按钮样式(来自 Figma)"
# 5. 推送并创建 PR
git push origin design/new-button-style
代码 Review Checklist
## 设计稿代码 Review
- [ ] 样式数值与 Figma 一致(使用浏览器插件对比)
- [ ] 响应式断点符合设计规范
- [ ] 颜色使用了设计 Token(而非硬编码)
- [ ] 无障碍性测试通过(WAVE/axe DevTools)
- [ ] 性能指标正常(Lighthouse Score > 90)
- [ ] 代码符合团队规范(通过 ESLint/Prettier)
4. 团队协作最佳实践
角色分工
| 角色 | 职责 | 使用 MCP 的方式 |
|---|---|---|
| 设计师 | 维护 Figma 源文件 | 使用 Figma Annotations 标注交互 |
| 前端 Leader | 配置 MCP,审核生成代码 | 编写 Prompt 模板库 |
| 前端开发 | 微调 AI 生成的代码 | 使用预设 Prompt 生成组件 |
| 测试工程师 | 对比设计稿与实现 | 用 MCP 提取设计规范做自动化测试 |
Prompt 模板库
创建团队共享的提示词库:
// prompts/component-generator.js
export const COMPONENT_PROMPTS = {
button: `
生成 Button 组件,遵循以下规范:
技术栈:
- React 18 + TypeScript
- Tailwind CSS
- Radix UI(无障碍基础)
Props:
- variant: 'primary' | 'secondary' | 'ghost'
- size: 'sm' | 'md' | 'lg'
- isLoading: boolean
- leftIcon / rightIcon: ReactNode
额外要求:
- 遵循 WCAG 2.1 AA 标准
- 支持键盘导航
- 包含 Storybook 文档
- 生成单元测试
`,
form: `
生成 Form 组件,集成 React Hook Form。
包含:
- 字段验证(Zod schema)
- 错误提示
- 提交状态管理
- 无障碍错误通告
`,
};
// 使用
const prompt = COMPONENT_PROMPTS.button + `
现在分析 Figma 文件 ${fileId} 中的 "Button/Primary"
`;
设计交接文档
# 设计交接:新按钮组件
## Figma 链接
https://figma.com/file/ABC123/Buttons
## 变更说明
- 主按钮新增 "medium" 尺寸
- Hover 状态调整为渐变背景
- 增加 loading 状态的 spinner
## Claude 生成指令
使用 Figma MCP 读取文件 ABC123,查找组件 "Button/Primary/Medium",生成符合团队规范的 React 代码。
参考现有组件:src/components/Button/Button.tsx保持 API 一致性。
## 验收标准
- [ ] 视觉还原度 100%(对比 Figma)
- [ ] 支持深色模式
- [ ] 通过 Axe 无障碍测试
- [ ] Storybook 文档完整
📝 总结
两种方案优缺点回顾
官方 MCP
优势:
- ✅ 零配置,开箱即用
- ✅ 官方维护,稳定可靠
- ✅ OAuth 授权,安全性高
限制:
- ⚠️ 每月额度有限
- ⚠️ 功能相对基础
适合:初学者、轻度使用、快速验证想法
非官方 MCP
优势:
- ✅ 无频率限制(取决于 Figma API)
- ✅ 功能更丰富
- ✅ 可编程调用
挑战:
- ⚠️ 需要配置 API Key
- ⚠️ 需要维护配置文件
适合:频繁使用、生产环境、自动化场景
🎉 结语
从设计稿到代码,不再是苦差事,而是创造性的对话。
通过 Claude Code + Figma MCP,你获得了: - ⏱️ 60% 的时间节省 - 🎯 100% 的设计还原度 - 🚀 10倍的迭代速度 记住:**AI 是工具,你的设计理解和工程判断才是核心价值。
现在,打开你的 Figma,开始你的第一次 AI 辅助开发之旅吧!
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)