figma-use

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

use_figma — Figma Plugin API Skill

use_figma — Figma Plugin API 技能

Use
use_figma
MCP to execute JavaScript in Figma files via the Plugin API. All detailed reference docs live in
references/
.
Always pass
skillNames: "figma-use"
when calling
use_figma
.
This is a logging parameter used to track skill usage — it does not affect execution.
If the task involves building or updating a full page, screen, or multi-section layout in Figma from code, also load figma-generate-design. It provides the workflow for discovering design system components via
search_design_system
, importing them, and assembling screens incrementally. Both skills work together: this one for the API rules, that one for the screen-building workflow.
Before anything, load plugin-api-standalone.index.md to understand what is possible. When you are asked to write plugin API code, use this context to grep plugin-api-standalone.d.ts for relevant types, methods, and properties. This is the definitive source of truth for the API surface. It is a large typings file, so do not load it all at once, grep for relevant sections as needed.
IMPORTANT: Whenever you work with design systems, start with working-with-design-systems/wwds.md to understand the key concepts, processes, and guidelines for working with design systems in Figma. Then load the more specific references for components, variables, text styles, and effect styles as needed.
使用
use_figma
MCP通过Plugin API在Figma文件中执行JavaScript。所有详细参考文档都位于
references/
目录下。
**调用
use_figma
时必须传入
skillNames: "figma-use"
。**这是一个用于跟踪技能使用情况的日志参数——不会影响执行。
如果任务涉及从代码在Figma中构建或更新完整页面、屏幕或多节布局,还需加载figma-generate-design。它提供了通过
search_design_system
发现设计系统组件、导入组件并逐步组装屏幕的工作流。这两个技能可以协同工作:本技能负责API规则,而另一个技能负责屏幕构建工作流。
在开始任何操作之前,请先加载plugin-api-standalone.index.md以了解可实现的功能。当需要编写Plugin API代码时,请使用此上下文在plugin-api-standalone.d.ts中搜索相关类型、方法和属性。这是API接口的权威来源。这是一个大型类型定义文件,因此不要一次性全部加载,而是根据需要搜索相关部分。
重要提示:处理设计系统时,请先从working-with-design-systems/wwds.md开始,了解在Figma中处理设计系统的关键概念、流程和指南。然后根据需要加载关于组件、变量、文本样式和效果样式的更具体参考文档。

1. Critical Rules

1. 关键规则

  1. Use
    return
    to send data back.
    The return value is JSON-serialized automatically (objects, arrays, strings, numbers). Do NOT call
    figma.closePlugin()
    or wrap code in an async IIFE — this is handled for you.
  2. Write plain JavaScript with top-level
    await
    and
    return
    .
    Code is automatically wrapped in an async context. Do NOT wrap in
    (async () => { ... })()
    .
  3. figma.notify()
    throws "not implemented" — never use it 3a.
    getPluginData()
    /
    setPluginData()
    are not supported in
    use_figma
    — do not use them. Use
    getSharedPluginData()
    /
    setSharedPluginData()
    instead (these ARE supported), or track node IDs by returning them and passing them to subsequent calls.
  4. console.log()
    is NOT returned — use
    return
    for output
  5. Work incrementally in small steps. Break large operations into multiple
    use_figma
    calls. Validate after each step. This is the single most important practice for avoiding bugs.
  6. Colors are 0–1 range (not 0–255):
    {r: 1, g: 0, b: 0}
    = red
  7. Fills/strokes are read-only arrays — clone, modify, reassign
  8. Font MUST be loaded before any text operation:
    await figma.loadFontAsync({family, style})
  9. Pages load incrementally — use
    await figma.setCurrentPageAsync(page)
    to switch pages and load their content (see Page Rules below)
  10. setBoundVariableForPaint
    returns a NEW paint — must capture and reassign
  11. createVariable
    accepts collection object or ID string (object preferred)
  12. layoutSizingHorizontal/Vertical = 'FILL'
    MUST be set AFTER
    parent.appendChild(child)
    — setting before append throws. Same applies to
    'HUG'
    on non-auto-layout nodes.
  13. Position new top-level nodes away from (0,0). Nodes appended directly to the page default to (0,0). Scan
    figma.currentPage.children
    to find a clear position (e.g., to the right of the rightmost node). This only applies to page-level nodes — nodes nested inside other frames or auto-layout containers are positioned by their parent. See Gotchas.
  14. On
    use_figma
    error, STOP. Do NOT immediately retry.
    Failed scripts are atomic — if a script errors, it is not executed at all and no changes are made to the file. Read the error message carefully, fix the script, then retry. See Error Recovery.
  15. MUST
    return
    ALL created/mutated node IDs.
    Whenever a script creates new nodes or mutates existing ones on the canvas, collect every affected node ID and return them in a structured object (e.g.
    return { createdNodeIds: [...], mutatedNodeIds: [...] }
    ). This is essential for subsequent calls to reference, validate, or clean up those nodes.
  16. Always set
    variable.scopes
    explicitly when creating variables.
    The default
    ALL_SCOPES
    pollutes every property picker — almost never what you want. Use specific scopes like
    ["FRAME_FILL", "SHAPE_FILL"]
    for backgrounds,
    ["TEXT_FILL"]
    for text colors,
    ["GAP"]
    for spacing, etc. See variable-patterns.md for the full list.
  17. await
    every Promise.
    Never leave a Promise unawaited — unawaited async calls (e.g.
    figma.loadFontAsync(...)
    without
    await
    , or
    figma.setCurrentPageAsync(page)
    without
    await
    ) will fire-and-forget, causing silent failures or race conditions. The script may return before the async operation completes, leading to missing data or half-applied changes.
For detailed WRONG/CORRECT examples of each rule, see Gotchas & Common Mistakes.
  1. 使用
    return
    返回数据
    。返回值会自动序列化为JSON(对象、数组、字符串、数字)。请勿调用
    figma.closePlugin()
    或将代码包装在异步立即执行函数(async IIFE)中——这些操作会自动处理。
  2. 编写包含顶级
    await
    return
    的纯JavaScript代码
    。代码会自动包装在异步上下文中。请勿将代码包装在
    (async () => { ... })()
    中。
  3. figma.notify()
    会抛出"not implemented"错误——绝对不要使用它 3a.
    getPluginData()
    /
    setPluginData()
    use_figma
    不受支持——请勿使用。请改用
    getSharedPluginData()
    /
    setSharedPluginData()
    (这些是受支持的),或者通过返回节点ID并在后续调用中传递来跟踪节点。
  4. console.log()
    的输出不会返回——请使用
    return
    进行输出
  5. 逐步增量操作。将大型操作拆分为多个
    use_figma
    调用。每一步后进行验证。这是避免错误最重要的做法。
  6. 颜色值使用0–1范围(而非0–255):
    {r: 1, g: 0, b: 0}
    表示红色
  7. 填充/描边是只读数组——请克隆、修改后重新赋值
  8. 字体必须在任何文本操作前加载:
    await figma.loadFontAsync({family, style})
  9. 页面增量加载——使用
    await figma.setCurrentPageAsync(page)
    切换页面并加载其内容(见下文页面规则)
  10. setBoundVariableForPaint
    会返回一个新的填充对象——必须捕获并重新赋值
  11. createVariable
    接受集合对象或ID字符串(优先使用对象)
  12. layoutSizingHorizontal/Vertical = 'FILL'
    必须在
    parent.appendChild(child)
    之后设置
    ——在追加前设置会抛出错误。对于非自动布局节点设置
    'HUG'
    也是如此。
  13. 将新的顶级节点放置在远离(0,0)的位置。直接追加到页面的节点默认位置是(0,0)。请扫描
    figma.currentPage.children
    以找到一个空白位置(例如,最右侧节点的右侧)。这仅适用于页面级节点——嵌套在其他框架或自动布局容器中的节点由其父节点定位。详见注意事项
  14. 如果
    use_figma
    调用出错,请停止操作。不要立即重试。失败的脚本是原子性
    的——如果脚本出错,它根本不会执行,也不会对文件进行任何更改。请仔细阅读错误消息,修复脚本后再重试。详见错误恢复
  15. 必须
    return
    所有创建/修改的节点ID
    。每当脚本在画布上创建新节点或修改现有节点时,请收集所有受影响的节点ID并以结构化对象返回(例如
    return { createdNodeIds: [...], mutatedNodeIds: [...] }
    )。这对于后续调用引用、验证或清理这些节点至关重要。
  16. 创建变量时必须显式设置
    variable.scopes
    。默认的
    ALL_SCOPES
    会污染每个属性选择器——几乎从来都不是你想要的结果。请使用特定范围,例如用于背景的
    ["FRAME_FILL", "SHAPE_FILL"]
    、用于文本颜色的
    ["TEXT_FILL"]
    、用于间距的
    ["GAP"]
    等。完整列表请见variable-patterns.md
  17. 所有Promise都必须
    await
    。永远不要让Promise处于未等待状态——未等待的异步调用(例如不带
    await
    figma.loadFontAsync(...)
    ,或不带
    await
    figma.setCurrentPageAsync(page)
    )会触发即发即弃,导致静默失败或竞态条件。脚本可能在异步操作完成前返回,导致数据缺失或部分应用的更改。
每个规则的详细错误/正确示例,请见注意事项与常见错误

2. Page Rules (Critical)

2. 页面规则(关键)

Page context resets between
use_figma
calls
figma.currentPage
starts on the first page each time.
use_figma
调用之间页面上下文会重置
——每次调用时
figma.currentPage
都会从第一页开始。

Switching pages

切换页面

Use
await figma.setCurrentPageAsync(page)
to switch pages and load their content. The sync setter
figma.currentPage = page
throws an error in
use_figma
runtimes.
js
// Switch to a specific page (loads its content)
const targetPage = figma.root.children.find((p) => p.name === "My Page");
await figma.setCurrentPageAsync(targetPage);
// targetPage.children is now populated

// Iterate over all pages
for (const page of figma.root.children) {
  await figma.setCurrentPageAsync(page);
  // page.children is now loaded — read or modify them here
}
使用
await figma.setCurrentPageAsync(page)
切换页面并加载其内容。同步设置器
figma.currentPage = page
use_figma
运行时会抛出错误
js
// 切换到指定页面(加载其内容)
const targetPage = figma.root.children.find((p) => p.name === "My Page");
await figma.setCurrentPageAsync(targetPage);
// 现在targetPage.children已加载完成

// 遍历所有页面
for (const page of figma.root.children) {
  await figma.setCurrentPageAsync(page);
  // page.children已加载——在此处读取或修改它们
}

Across script runs

跨脚本调用

figma.currentPage
resets to the first page at the start of each
use_figma
call. If your workflow spans multiple calls and targets a non-default page, call
await figma.setCurrentPageAsync(page)
at the start of each invocation.
You can call
use_figma
multiple times to incrementally build on the file state, or to retrieve information before writing another script. For example, write a script to get metadata about existing nodes,
return
that data, then use it in a subsequent script to modify those nodes.
每次
use_figma
调用开始时,
figma.currentPage
都会重置为第一页。如果工作流跨多个调用且目标为非默认页面,请在每次调用开始时调用
await figma.setCurrentPageAsync(page)
你可以多次调用
use_figma
以逐步构建文件状态,或在编写另一个脚本前检索信息。例如,先编写一个脚本获取现有节点的元数据,
return
该数据,然后在后续脚本中使用它来修改这些节点。

3.
return
Is Your Output Channel

3.
return
是你的输出通道

The agent sees ONLY the value you
return
. Everything else is invisible.
  • Returning IDs (CRITICAL): Every script that creates or mutates canvas nodes MUST return all affected node IDs — e.g.
    return { createdNodeIds: [...], mutatedNodeIds: [...] }
    . This is a hard requirement, not optional.
  • Progress reporting:
    return { createdNodeIds: [...], count: 5, errors: [] }
  • Error info: Thrown errors are automatically captured and returned — just let them propagate or
    throw
    explicitly.
  • console.log()
    output is never returned to the agent
  • Always return actionable data (IDs, counts, status) so subsequent calls can reference created objects
Agent只能看到
return
的值。其他所有内容都是不可见的。
  • 返回ID(至关重要):每个创建或修改画布节点的脚本必须返回所有受影响的节点ID——例如
    return { createdNodeIds: [...], mutatedNodeIds: [...] }
    。这是硬性要求,而非可选操作。
  • 进度报告
    return { createdNodeIds: [...], count: 5, errors: [] }
  • 错误信息:抛出的错误会自动捕获并返回——只需让错误传播或显式
    throw
    即可。
  • console.log()
    的输出永远不会返回给Agent
  • 始终返回可操作的数据(ID、计数、状态),以便后续调用可以引用创建的对象

4. Editor Mode

4. 编辑器模式

use_figma
works in design mode (editorType
"figma"
, the default). FigJam (
"figjam"
) has a different set of available node types — most design nodes are blocked there.
Available in design mode: Rectangle, Frame, Component, Text, Ellipse, Star, Line, Vector, Polygon, BooleanOperation, Slice, Page, Section, TextPath.
Blocked in design mode: Sticky, Connector, ShapeWithText, CodeBlock, Slide, SlideRow, Webpage.
use_figma
设计模式(editorType为
"figma"
,默认模式)下工作。FigJam(
"figjam"
)有一组不同的可用节点类型——大多数设计节点在那里是被阻止的。
设计模式下可用的节点:Rectangle、Frame、Component、Text、Ellipse、Star、Line、Vector、Polygon、BooleanOperation、Slice、Page、Section、TextPath。
设计模式下被阻止的节点:Sticky、Connector、ShapeWithText、CodeBlock、Slide、SlideRow、Webpage。

5. Incremental Workflow (How to Avoid Bugs)

5. 增量工作流(如何避免错误)

The most common cause of bugs is trying to do too much in a single
use_figma
call. Work in small steps and validate after each one.
错误最常见的原因是试图在单个
use_figma
调用中完成过多操作。请分小步骤操作,并在每一步后进行验证。

The pattern

模式

  1. Inspect first. Before creating anything, run a read-only
    use_figma
    to discover what already exists in the file — pages, components, variables, naming conventions. Match what's there.
  2. Do one thing per call. Create variables in one call, create components in the next, compose layouts in another. Don't try to build an entire screen in one script.
  3. Return IDs from every call. Always
    return
    created node IDs, variable IDs, collection IDs as objects (e.g.
    return { createdNodeIds: [...] }
    ). You'll need these as inputs to subsequent calls.
  4. Validate after each step. Use
    get_metadata
    to verify structure (counts, names, hierarchy, positions). Use
    get_screenshot
    after major milestones to catch visual issues.
  5. Fix before moving on. If validation reveals a problem, fix it before proceeding to the next step. Don't build on a broken foundation.
  1. 先检查。在创建任何内容之前,运行一个只读的
    use_figma
    调用以发现文件中已有的内容——页面、组件、变量、命名约定。与现有内容保持一致。
  2. 每次调用完成一件事。在一个调用中创建变量,在下一个调用中创建组件,在另一个调用中组合布局。不要试图在一个脚本中构建整个屏幕。
  3. 每次调用都返回ID。始终以对象形式返回创建的节点ID、变量ID、集合ID(例如
    return { createdNodeIds: [...] }
    )。后续调用需要这些作为输入。
  4. 每一步后验证。使用
    get_metadata
    验证结构(计数、名称、层级、位置)。在重要里程碑后使用
    get_screenshot
    捕获视觉问题。
  5. 修复后再继续。如果验证发现问题,请在进行下一步前修复。不要在有问题的基础上继续构建。

Suggested step order for complex tasks

复杂任务的建议步骤顺序

Step 1: Inspect file — discover existing pages, components, variables, conventions
Step 2: Create tokens/variables (if needed)
       → validate with get_metadata
Step 3: Create individual components
       → validate with get_metadata + get_screenshot
Step 4: Compose layouts from component instances
       → validate with get_screenshot
Step 5: Final verification
步骤1:检查文件——发现现有页面、组件、变量、命名约定
步骤2:创建令牌/变量(如果需要)
       → 使用get_metadata验证
步骤3:创建单个组件
       → 使用get_metadata + get_screenshot验证
步骤4:从组件实例组合布局
       → 使用get_screenshot验证
步骤5:最终验证

What to validate at each step

每一步的验证内容

After...Check with
get_metadata
Check with
get_screenshot
Creating variablesCollection count, variable count, mode names
Creating componentsChild count, variant names, property definitionsVariants visible, not collapsed, grid readable
Binding variablesNode properties reflect bindingsColors/tokens resolved correctly
Composing layoutsInstance nodes have mainComponent, hierarchy correctNo cropped/clipped text, no overlapping elements, correct spacing
操作后...使用
get_metadata
检查
使用
get_screenshot
检查
创建变量集合数量、变量数量、模式名称
创建组件子节点数量、变体名称、属性定义变体可见、未折叠、网格可读
绑定变量节点属性反映绑定关系颜色/令牌解析正确
组合布局实例节点包含mainComponent、层级正确文本无裁剪、元素无重叠、间距正确

6. Error Recovery & Self-Correction

6. 错误恢复与自我修正

use_figma
is atomic — failed scripts do not execute.
If a script errors, no changes are made to the file. The file remains in the same state as before the call. This means there are no partial nodes, no orphaned elements from the failed script, and retrying after a fix is safe.
**
use_figma
是原子性的——失败的脚本不会执行。**如果脚本出错,不会对文件进行任何更改。文件会保持调用前的状态。这意味着不会有部分节点、失败脚本留下的孤立元素,修复后重试是安全的。

When
use_figma
returns an error

use_figma
返回错误时

  1. STOP. Do not immediately fix the code and retry.
  2. Read the error message carefully. Understand exactly what went wrong — wrong API usage, missing font, invalid property value, etc.
  3. If the error is unclear, call
    get_metadata
    or
    get_screenshot
    to understand the current file state.
  4. Fix the script based on the error message.
  5. Retry the corrected script.
  1. 停止操作。不要立即修复代码并重试。
  2. 仔细阅读错误消息。准确理解出错原因——API使用错误、字体缺失、属性值无效等。
  3. 如果错误不明确,调用
    get_metadata
    get_screenshot
    以了解当前文件状态。
  4. 根据错误消息修复脚本
  5. 重试修正后的脚本。

Common self-correction patterns

常见自我修正模式

Error messageLikely causeHow to fix
"not implemented"
Used
figma.notify()
Remove it — use
return
for output
"node must be an auto-layout frame..."
Set
FILL
/
HUG
before appending to auto-layout parent
Move
appendChild
before
layoutSizingX = 'FILL'
"Setting figma.currentPage is not supported"
Used sync page setterUse
await figma.setCurrentPageAsync(page)
Property value out of rangeColor channel > 1 (used 0–255 instead of 0–1)Divide by 255
"Cannot read properties of null"
Node doesn't exist (wrong ID, wrong page)Check page context, verify ID
Script hangs / no responseInfinite loop or unresolved promiseCheck for
while(true)
or missing
await
; ensure code terminates
"The node with id X does not exist"
Parent instance was implicitly detached by a child
detachInstance()
, changing IDs
Re-discover nodes by traversal from a stable (non-instance) parent frame
错误消息可能原因修复方法
"not implemented"
使用了
figma.notify()
删除它——使用
return
进行输出
"node must be an auto-layout frame..."
在追加到自动布局父节点前设置了
FILL
/
HUG
appendChild
移到
layoutSizingX = 'FILL'
之前
"Setting figma.currentPage is not supported"
使用了同步页面设置器使用
await figma.setCurrentPageAsync(page)
属性值超出范围颜色通道值>1(使用了0–255而非0–1)将值除以255
"Cannot read properties of null"
节点不存在(错误的ID、错误的页面)检查页面上下文,验证ID
脚本挂起/无响应无限循环或未解决的Promise检查是否有
while(true)
或缺失的
await
;确保代码可以终止
"The node with id X does not exist"
父实例被子节点的
detachInstance()
隐式分离,导致ID更改
从稳定的(非实例)父框架遍历重新发现节点

When the script succeeds but the result looks wrong

当脚本成功但结果看起来不正确时

  1. Call
    get_metadata
    to check structural correctness (hierarchy, counts, positions).
  2. Call
    get_screenshot
    to check visual correctness. Look closely for cropped/clipped text (line heights cutting off content) and overlapping elements — these are common and easy to miss.
  3. Identify the discrepancy — is it structural (wrong hierarchy, missing nodes) or visual (wrong colors, broken layout, clipped content)?
  4. Write a targeted fix script that modifies only the broken parts — don't recreate everything.
For the full validation workflow, see Validation & Error Recovery.
  1. 调用
    get_metadata
    检查结构正确性(层级、计数、位置)。
  2. 调用
    get_screenshot
    检查视觉正确性。仔细查看是否有文本裁剪(行高截断内容)和元素重叠——这些是常见且容易被忽略的问题。
  3. 识别差异——是结构问题(错误的层级、缺失节点)还是视觉问题(错误的颜色、布局损坏、内容裁剪)?
  4. 编写有针对性的修复脚本,仅修改有问题的部分——不要重新创建所有内容。
完整的验证工作流,请见验证与错误恢复

7. Pre-Flight Checklist

7. 预检查清单

Before submitting ANY
use_figma
call, verify:
  • Code uses
    return
    to send data back (NOT
    figma.closePlugin()
    )
  • Code is NOT wrapped in an async IIFE (auto-wrapped for you)
  • return
    value includes structured data with actionable info (IDs, counts)
  • NO usage of
    figma.notify()
    anywhere
  • NO usage of
    console.log()
    as output (use
    return
    instead)
  • All colors use 0–1 range (not 0–255)
  • Fills/strokes are reassigned as new arrays (not mutated in place)
  • Page switches use
    await figma.setCurrentPageAsync(page)
    (sync setter throws)
  • layoutSizingVertical/Horizontal = 'FILL'
    is set AFTER
    parent.appendChild(child)
  • loadFontAsync()
    called BEFORE any text property changes
  • lineHeight
    /
    letterSpacing
    use
    {unit, value}
    format (not bare numbers)
  • resize()
    is called BEFORE setting sizing modes (resize resets them to FIXED)
  • For multi-step workflows: IDs from previous calls are passed as string literals (not variables)
  • New top-level nodes are positioned away from (0,0) to avoid overlapping existing content
  • ALL created/mutated node IDs are collected and included in the
    return
    value
  • Every async call (
    loadFontAsync
    ,
    setCurrentPageAsync
    ,
    importComponentByKeyAsync
    , etc.) is
    await
    ed — no fire-and-forget Promises
在提交任何
use_figma
调用之前,请验证:
  • 代码使用
    return
    返回数据(而非
    figma.closePlugin()
  • 代码未包装在异步立即执行函数中(会自动包装)
  • 返回值包含带有可操作信息的结构化数据(ID、计数)
  • 未在任何地方使用
    figma.notify()
  • 未将
    console.log()
    用作输出(请改用
    return
  • 所有颜色使用0–1范围(而非0–255)
  • 填充/描边被重新赋值为新数组(而非就地修改)
  • 页面切换使用
    await figma.setCurrentPageAsync(page)
    (同步设置器会抛出错误)
  • layoutSizingVertical/Horizontal = 'FILL'
    parent.appendChild(child)
    之后设置
  • 在任何文本属性更改前调用了
    loadFontAsync()
  • lineHeight
    /
    letterSpacing
    使用
    {unit, value}
    格式(而非裸数字)
  • 在设置大小模式前调用了
    resize()
    (resize会将大小模式重置为FIXED)
  • 对于多步骤工作流:前一次调用的ID作为字符串字面量传递(而非变量)
  • 新的顶级节点被放置在远离(0,0)的位置,以避免与现有内容重叠
  • 所有创建/修改的节点ID都被收集并包含在返回值中
  • 所有异步调用(
    loadFontAsync
    setCurrentPageAsync
    importComponentByKeyAsync
    等)都被
    await
    ——没有即发即弃的Promise

8. Discover Conventions Before Creating

8. 创建前先发现约定

Always inspect the Figma file before creating anything. Different files use different naming conventions, variable structures, and component patterns. Your code should match what's already there, not impose new conventions.
When in doubt about any convention (naming, scoping, structure), check the Figma file first, then the user's codebase. Only fall back to common patterns when neither exists.
**在创建任何内容之前,请始终检查Figma文件。**不同的文件使用不同的命名约定、变量结构和组件模式。你的代码应与现有内容保持一致,而非强加新约定。
对任何约定(命名、范围、结构)有疑问时,请先检查Figma文件,再检查用户的代码库。仅当两者都不存在时,才使用常见模式。

Quick inspection scripts

快速检查脚本

List all pages and top-level nodes:
js
const pages = figma.root.children.map(p => `${p.name} id=${p.id} children=${p.children.length}`);
return pages.join('\n');
List existing components across all pages:
js
const results = [];
for (const page of figma.root.children) {
  await figma.setCurrentPageAsync(page);
  page.findAll(n => {
    if (n.type === 'COMPONENT' || n.type === 'COMPONENT_SET')
      results.push(`[${page.name}] ${n.name} (${n.type}) id=${n.id}`);
    return false;
  });
}
return results.join('\n');
List existing variable collections and their conventions:
js
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const results = collections.map(c => ({
  name: c.name, id: c.id,
  varCount: c.variableIds.length,
  modes: c.modes.map(m => m.name)
}));
return results;
列出所有页面和顶级节点:
js
const pages = figma.root.children.map(p => `${p.name} id=${p.id} children=${p.children.length}`);
return pages.join('\n');
列出所有页面中的现有组件:
js
const results = [];
for (const page of figma.root.children) {
  await figma.setCurrentPageAsync(page);
  page.findAll(n => {
    if (n.type === 'COMPONENT' || n.type === 'COMPONENT_SET')
      results.push(`[${page.name}] ${n.name} (${n.type}) id=${n.id}`);
    return false;
  });
}
return results.join('\n');
列出现有变量集合及其约定:
js
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const results = collections.map(c => ({
  name: c.name, id: c.id,
  varCount: c.variableIds.length,
  modes: c.modes.map(m => m.name)
}));
return results;

9. Reference Docs

9. 参考文档

Load these as needed based on what your task involves:
DocWhen to loadWhat it covers
gotchas.mdBefore any
use_figma
Every known pitfall with WRONG/CORRECT code examples
common-patterns.mdNeed working code examplesScript scaffolds: shapes, text, auto-layout, variables, components, multi-step workflows
plugin-api-patterns.mdCreating/editing nodesFills, strokes, Auto Layout, effects, grouping, cloning, styles
api-reference.mdNeed exact API surfaceNode creation, variables API, core properties, what works and what doesn't
validation-and-recovery.mdMulti-step writes or error recovery
get_metadata
vs
get_screenshot
workflow, mandatory error recovery steps
component-patterns.mdCreating components/variantscombineAsVariants, component properties, INSTANCE_SWAP, variant layout, discovering existing components, metadata traversal
variable-patterns.mdCreating/binding variablesCollections, modes, scopes, aliasing, binding patterns, discovering existing variables
text-style-patterns.mdCreating/applying text stylesType ramps, font probing, listing styles, applying styles to nodes
effect-style-patterns.mdCreating/applying effect stylesDrop shadows, listing styles, applying styles to nodes
plugin-api-standalone.index.mdNeed to understand the full API surfaceIndex of all types, methods, and properties in the Plugin API
plugin-api-standalone.d.tsNeed exact type signaturesFull typings file — grep for specific symbols, don't load all at once
根据任务需求按需加载以下文档:
文档加载时机涵盖内容
gotchas.md任何
use_figma
调用之前
所有已知陷阱及错误/正确代码示例
common-patterns.md需要可用代码示例时脚本模板:形状、文本、自动布局、变量、组件、多步骤工作流
plugin-api-patterns.md创建/编辑节点时填充、描边、自动布局、效果、分组、克隆、样式
api-reference.md需要精确API接口时节点创建、变量API、核心属性、支持与不支持的功能
validation-and-recovery.md多步骤写入或错误恢复时
get_metadata
get_screenshot
工作流、强制错误恢复步骤
component-patterns.md创建组件/变体时combineAsVariants、组件属性、INSTANCE_SWAP、变体布局、发现现有组件、元数据遍历
variable-patterns.md创建/绑定变量时集合、模式、范围、别名、绑定模式、发现现有变量
text-style-patterns.md创建/应用文本样式时类型阶梯、字体探测、列出样式、将样式应用到节点
effect-style-patterns.md创建/应用效果样式时阴影、列出样式、将样式应用到节点
plugin-api-standalone.index.md需要了解完整API接口时Plugin API中所有类型、方法和属性的索引
plugin-api-standalone.d.ts需要精确类型签名时完整类型定义文件——搜索特定符号,不要一次性全部加载

10. Snippet examples

10. 代码片段示例

You will see snippets throughout documentation here. These snippets contain useful plugin API code that can be repurposed. Use them as is, or as starter code as you go. If there are key concepts that are best documented as generic snippets, call them out and write to disk so you can reuse in the future.
你会在此文档中看到各种代码片段。这些片段包含可复用的实用Plugin API代码。请直接使用它们,或将其作为起始代码。如果有最佳通过通用片段记录的关键概念,请标注出来并写入磁盘,以便将来复用。