figma-code-connect

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Overview

概述

Create parserless Code Connect template files (
.figma.js
) that map Figma components to code snippets. Given a Figma URL, follow the steps below to create a template.
Note: This project may also contain parser-based
.figma.tsx
files (using
figma.connect()
, published via CLI). This skill covers parserless templates only
.figma.js
files that use the MCP tools to fetch component context from Figma.
创建无解析器的Code Connect模板文件(
.figma.js
),用于将Figma组件映射到代码片段。给定Figma URL后,按照以下步骤创建模板。
注意: 本项目可能也包含带解析器的
.figma.tsx
文件(使用
figma.connect()
,通过CLI发布)。本技能仅覆盖无解析器模板——即通过MCP工具从Figma获取组件上下文的
.figma.js
文件。

Prerequisites

前提条件

  • Figma MCP server must be connected — verify that Figma MCP tools (e.g.,
    get_code_connect_suggestions
    ) are available before proceeding. If not, guide the user to enable the Figma MCP server and restart their MCP client.
  • Components must be published — Code Connect only works with components published to a Figma team library. If a component is not published, inform the user and stop.
  • Organization or Enterprise plan required — Code Connect is not available on Free or Professional plans.
  • URL must include
    node-id
    — the Figma URL must contain the
    node-id
    query parameter.
  • 必须连接Figma MCP服务器——操作前请确认
    get_code_connect_suggestions
    等Figma MCP工具可用。如果不可用,引导用户启用Figma MCP服务器并重启MCP客户端。
  • 组件必须已发布——Code Connect仅支持发布到Figma团队库的组件。如果组件未发布,告知用户后终止操作。
  • 需要组织版或企业版计划——免费版和专业版计划不支持Code Connect。
  • URL必须包含
    node-id
    ——Figma URL必须带有
    node-id
    查询参数。

Step 1: Parse the Figma URL

步骤1:解析Figma URL

Extract
fileKey
and
nodeId
from the URL:
URL FormatfileKeynodeId
figma.com/design/:fileKey/:name?node-id=X-Y
:fileKey
X-Y
X:Y
figma.com/file/:fileKey/:name?node-id=X-Y
:fileKey
X-Y
X:Y
figma.com/design/:fileKey/branch/:branchKey/:name
use
:branchKey
from
node-id
param
Always convert
nodeId
hyphens to colons:
1234-5678
1234:5678
.
Worked example:
Given:
https://www.figma.com/design/QiEF6w564ggoW8ftcLvdcu/MyDesignSystem?node-id=4185-3778
  • fileKey
    =
    QiEF6w564ggoW8ftcLvdcu
  • nodeId
    =
    4185-3778
    4185:3778
从URL中提取
fileKey
nodeId
URL格式fileKeynodeId
figma.com/design/:fileKey/:name?node-id=X-Y
:fileKey
X-Y
X:Y
figma.com/file/:fileKey/:name?node-id=X-Y
:fileKey
X-Y
X:Y
figma.com/design/:fileKey/branch/:branchKey/:name
使用
:branchKey
node-id
参数获取
始终将
nodeId
中的连字符转换为冒号:
1234-5678
1234:5678
示例:
给定URL:
https://www.figma.com/design/QiEF6w564ggoW8ftcLvdcu/MyDesignSystem?node-id=4185-3778
  • fileKey
    =
    QiEF6w564ggoW8ftcLvdcu
  • nodeId
    =
    4185-3778
    4185:3778

Step 2: Discover Unmapped Components

步骤2:查找未映射的组件

The user may provide a URL pointing to a frame, instance, or variant — not necessarily a component set or standalone component. Call the MCP tool
get_code_connect_suggestions
with:
  • fileKey
    — from Step 1
  • nodeId
    — from Step 1 (colons format)
  • excludeMappingPrompt
    true
    (returns a lightweight list of unmapped components)
This tool identifies published components in the selection that don't yet have Code Connect mappings.
Handle the response:
  • "No published components found in this selection" — the node contains no published components. Inform the user they need to publish the component to a team library in Figma first, then stop.
  • "All component instances in this selection are already connected to code via Code Connect" — everything is already mapped. Inform the user and stop.
  • Normal response with component list — extract the
    mainComponentNodeId
    for each returned component. Use these resolved node IDs (not the original from the URL) for all subsequent steps. If multiple components are returned (e.g. the user selected a frame containing several different component instances), repeat Steps 3–6 for each one.
用户提供的URL可能指向框架、实例或变体,不一定是组件集或独立组件。调用MCP工具
get_code_connect_suggestions
,传入以下参数:
  • fileKey
    —— 来自步骤1
  • nodeId
    —— 来自步骤1(冒号格式)
  • excludeMappingPrompt
    ——
    true
    (返回轻量的未映射组件列表)
该工具会识别选中范围内尚未配置Code Connect映射的已发布组件。
响应处理:
  • "当前选中范围内未找到已发布组件" —— 节点不包含已发布组件。告知用户需要先将组件发布到Figma团队库,然后终止操作。
  • "当前选中范围内的所有组件实例都已通过Code Connect连接到代码" —— 所有组件都已完成映射,告知用户后终止操作。
  • 返回正常的组件列表 —— 为每个返回的组件提取
    mainComponentNodeId
    。后续所有步骤都使用这些解析后的节点ID(而非URL中的原始ID)。如果返回多个组件(例如用户选中了包含多个不同组件实例的框架),为每个组件重复步骤3-6。

Step 3: Fetch Component Properties

步骤3:获取组件属性

Call the MCP tool
get_context_for_code_connect
with:
  • fileKey
    — from Step 1
  • nodeId
    — the resolved
    mainComponentNodeId
    from Step 2
  • clientFrameworks
    — determine from
    figma.config.json
    parser
    field (e.g.
    "react"
    ["react"]
    )
  • clientLanguages
    — infer from project file extensions (e.g. TypeScript project →
    ["typescript"]
    , JavaScript →
    ["javascript"]
    )
For multiple components, call the tool once per node ID.
The response contains the Figma component's property definitions — note each property's name and type:
  • TEXT — text content (labels, titles, placeholders)
  • BOOLEAN — toggles (show/hide icon, disabled state)
  • VARIANT — enum options (size, variant, state)
  • INSTANCE_SWAP — swappable component slots (icon, avatar)
Save this property list — you will use it in Step 5 to write the template.
调用MCP工具
get_context_for_code_connect
,传入以下参数:
  • fileKey
    —— 来自步骤1
  • nodeId
    —— 步骤2解析得到的
    mainComponentNodeId
  • clientFrameworks
    —— 从
    figma.config.json
    parser
    字段判断(例如
    "react"
    ["react"]
  • clientLanguages
    —— 从项目文件后缀推断(例如TypeScript项目 →
    ["typescript"]
    ,JavaScript项目 →
    ["javascript"]
如果有多个组件,每个节点ID单独调用一次工具。
响应包含Figma组件的属性定义,请记录每个属性的名称和类型:
  • TEXT —— 文本内容(标签、标题、占位符)
  • BOOLEAN —— 开关项(显示/隐藏图标、禁用状态)
  • VARIANT —— 枚举选项(尺寸、变体、状态)
  • INSTANCE_SWAP —— 可交换的组件插槽(图标、头像)
保存该属性列表,步骤5编写模板时会用到。

Step 4: Identify the Code Component

步骤4:识别对应的代码组件

If the user did not specify which code component to connect:
  1. Check
    figma.config.json
    for
    paths
    and
    importPaths
    to find where components live
  2. Search the codebase for a component matching the Figma component name. Check common directories (
    src/components/
    ,
    components/
    ,
    lib/ui/
    ,
    app/components/
    ) if
    figma.config.json
    doesn't specify paths
  3. Read candidate files and compare their props interface against the Figma properties from Step 3 — look for matching variant types, size options, boolean flags, and slot props
  4. If multiple candidates match, pick the one with the closest prop-interface match and explain your reasoning to the user
  5. If no match is found, show the 2 closest candidates and ask the user to confirm or provide the correct path
Confirm with the user before proceeding to Step 5. Present the match: which code component you found, where it lives, and why it matches (prop correspondence, naming, purpose).
Read
figma.config.json
for import path aliases — the
importPaths
section maps glob patterns to import specifiers, and the
paths
section maps those specifiers to directories.
Read the code component's source to understand its props interface — this informs how to map Figma properties to code props in Step 5.
如果用户未指定要连接的代码组件:
  1. 检查
    figma.config.json
    中的
    paths
    importPaths
    ,找到组件存放位置
  2. 在代码库中搜索与Figma组件名称匹配的组件。如果
    figma.config.json
    未指定路径,检查常用目录(
    src/components/
    components/
    lib/ui/
    app/components/
  3. 读取候选文件,将其Props接口与步骤3得到的Figma属性对比,查找匹配的变体类型、尺寸选项、布尔标记和插槽Props
  4. 如果有多个匹配的候选组件,选择Props接口匹配度最高的一个,并向用户说明选择理由
  5. 如果未找到匹配项,展示最接近的2个候选组件,要求用户确认或提供正确的路径
进入步骤5前请先和用户确认,展示匹配结果:你找到的代码组件名称、存放位置,以及匹配的理由(Prop对应关系、命名、用途)。
读取
figma.config.json
中的导入路径别名:
importPaths
部分将glob模式映射到导入说明符,
paths
部分将说明符映射到目录。
读取代码组件的源码,了解其Props接口,这将帮助你在步骤5中完成Figma属性到代码Props的映射。

Step 5: Create the Parserless Template (.figma.js)

步骤5:创建无解析器模板(.figma.js)

File location

文件位置

Place the file alongside existing Code Connect templates (
.figma.tsx
or
.figma.js
files). Check
figma.config.json
include
patterns for the correct directory. Name it
ComponentName.figma.js
.
将文件放在现有Code Connect模板(
.figma.tsx
.figma.js
文件)的同级目录。查看
figma.config.json
include
规则确认正确目录,文件命名为
组件名.figma.js

Template structure

模板结构

Every parserless template follows this structure:
js
// url=https://www.figma.com/file/{fileKey}/{fileName}?node-id={nodeId}
// source={path to code component from Step 4}
// component={code component name from Step 4}
const figma = require('figma')
const instance = figma.selectedInstance

// Extract properties from the Figma component (see property mapping below)
// ...

export default {
  example: figma.tsx`<Component ... />`,       // Required: code snippet
  imports: ['import { Component } from "..."'], // Optional: import statements
  id: 'component-name',                         // Required: unique identifier
  metadata: {                                    // Optional
    nestable: true,                              // true = inline in parent, false = show as pill
    props: {}                                    // data accessible to parent templates
  }
}
所有无解析器模板都遵循以下结构:
js
// url=https://www.figma.com/file/{fileKey}/{fileName}?node-id={nodeId}
// source={步骤4得到的代码组件路径}
// component={步骤4得到的代码组件名称}
const figma = require('figma')
const instance = figma.selectedInstance

// 从Figma组件提取属性(参考下方属性映射)
// ...

export default {
  example: figma.tsx`<Component ... />`,       // 必填:代码片段
  imports: ['import { Component } from "..."'], // 可选:导入语句
  id: 'component-name',                         // 必填:唯一标识符
  metadata: {                                    // 可选
    nestable: true,                              // true = 父组件内联,false = 显示为pill
    props: {}                                    // 父模板可访问的数据
  }
}

Property mapping

属性映射

Use the property list from Step 3 to extract values. For each Figma property type, use the corresponding method:
Figma Property TypeTemplate MethodWhen to Use
TEXT
instance.getString('Name')
Labels, titles, placeholder text
BOOLEAN
instance.getBoolean('Name', { true: ..., false: ... })
Toggle visibility, conditional props
VARIANT
instance.getEnum('Name', { 'FigmaVal': 'codeVal' })
Size, variant, state enums
INSTANCE_SWAP
instance.getInstanceSwap('Name')
Icon slots, swappable children
(child layer)
instance.findInstance('LayerName')
Named child instances without a property
(text layer)
instance.findText('LayerName')
.textContent
Text content from named layers
TEXT — get the string value directly:
js
const label = instance.getString('Label')
VARIANT — map Figma enum values to code values:
js
const variant = instance.getEnum('Variant', {
  'Primary': 'primary',
  'Secondary': 'secondary',
})

const size = instance.getEnum('Size', {
  'Small': 'sm',
  'Medium': 'md',
  'Large': 'lg',
})
BOOLEAN — simple boolean or mapped to values:
js
// Simple boolean
const disabled = instance.getBoolean('Disabled')

// Mapped to code values
const hasIcon = instance.getBoolean('Has Icon', {
  true: figma.tsx`<Icon />`,
  false: undefined,
})
INSTANCE_SWAP — access swappable component instances:
js
const icon = instance.getInstanceSwap('Icon')
let iconCode
if (icon && icon.hasCodeConnect()) {
  iconCode = icon.executeTemplate().example
}
使用步骤3得到的属性列表提取值。针对每种Figma属性类型,使用对应的方法:
Figma属性类型模板方法使用场景
TEXT
instance.getString('名称')
标签、标题、占位文本
BOOLEAN
instance.getBoolean('名称', { true: ..., false: ... })
切换可见性、条件Props
VARIANT
instance.getEnum('名称', { 'Figma值': '代码值' })
尺寸、变体、状态枚举
INSTANCE_SWAP
instance.getInstanceSwap('名称')
图标插槽、可交换子组件
(子图层)
instance.findInstance('图层名')
未配置组件属性的命名子实例
(文本图层)
instance.findText('图层名')
.textContent
命名文本图层的文本内容
TEXT —— 直接获取字符串值:
js
const label = instance.getString('Label')
VARIANT —— 将Figma枚举值映射到代码值:
js
const variant = instance.getEnum('Variant', {
  'Primary': 'primary',
  'Secondary': 'secondary',
})

const size = instance.getEnum('Size', {
  'Small': 'sm',
  'Medium': 'md',
  'Large': 'lg',
})
BOOLEAN —— 简单布尔值或映射到指定值:
js
// 简单布尔值
const disabled = instance.getBoolean('Disabled')

// 映射到代码值
const hasIcon = instance.getBoolean('Has Icon', {
  true: figma.tsx`<Icon />`,
  false: undefined,
})
INSTANCE_SWAP —— 访问可交换的组件实例:
js
const icon = instance.getInstanceSwap('Icon')
let iconCode
if (icon && icon.hasCodeConnect()) {
  iconCode = icon.executeTemplate().example
}

Interpolation in tagged templates

标签模板插值

When interpolating values in tagged templates, use the correct wrapping:
  • String values (
    getString
    ,
    getEnum
    ,
    textContent
    ): wrap in quotes →
    variant="${variant}"
  • Instance/section values (
    executeTemplate().example
    ): wrap in braces →
    icon={${iconCode}}
  • Boolean bare props: use conditional →
    ${disabled ? 'disabled' : ''}
在标签模板中插值时,使用正确的包裹方式:
  • 字符串值
    getString
    getEnum
    textContent
    ):用引号包裹 →
    variant="${variant}"
  • 实例/区块值
    executeTemplate().example
    ):用大括号包裹 →
    icon={${iconCode}}
  • 布尔裸Props:使用条件表达式 →
    ${disabled ? 'disabled' : ''}

Finding descendant layers

查找后代图层

When you need to access children that aren't exposed as component properties:
MethodUse when
instance.getInstanceSwap('PropName')
A component property exists for this slot
instance.findInstance('LayerName')
You know the child layer name (no component property)
instance.findText('LayerName')
.textContent
You need text content from a named text layer
instance.findConnectedInstance('id')
You know the child's Code Connect
id
instance.findConnectedInstances(fn)
You need multiple connected children matching a filter
instance.findLayers(fn)
You need any layers (text + instances) matching a filter
当你需要访问未作为组件属性暴露的子元素时:
方法使用场景
instance.getInstanceSwap('属性名')
该插槽存在对应的组件属性
instance.findInstance('图层名')
你知道子图层的名称(无对应组件属性)
instance.findText('图层名')
.textContent
你需要从命名文本图层获取文本内容
instance.findConnectedInstance('id')
你知道子组件的Code Connect
id
instance.findConnectedInstances(fn)
你需要匹配筛选条件的多个关联子组件
instance.findLayers(fn)
你需要匹配筛选条件的任意图层(文本+实例)

Nested component example

嵌套组件示例

For multi-level nested components or metadata prop passing between templates, see advanced-patterns.md.
js
const icon = instance.getInstanceSwap('Icon')
let iconSnippet
if (icon && icon.hasCodeConnect()) {
  iconSnippet = icon.executeTemplate().example
}

export default {
  example: figma.tsx`<Button ${iconSnippet ? figma.tsx`icon={${iconSnippet}}` : ''}>${label}</Button>`,
  // ...
}
对于多级嵌套组件或模板间的元数据Props传递,参考advanced-patterns.md
js
const icon = instance.getInstanceSwap('Icon')
let iconSnippet
if (icon && icon.hasCodeConnect()) {
  iconSnippet = icon.executeTemplate().example
}

export default {
  example: figma.tsx`<Button ${iconSnippet ? figma.tsx`icon={${iconSnippet}}` : ''}>${label}</Button>`,
  // ...
}

Conditional props

条件Props

js
const variant = instance.getEnum('Variant', { 'Primary': 'primary', 'Secondary': 'secondary' })
const disabled = instance.getBoolean('Disabled')

export default {
  example: figma.tsx`
    <Button
      variant="${variant}"
      ${disabled ? 'disabled' : ''}
    >
      ${label}
    </Button>
  `,
  // ...
}
js
const variant = instance.getEnum('Variant', { 'Primary': 'primary', 'Secondary': 'secondary' })
const disabled = instance.getBoolean('Disabled')

export default {
  example: figma.tsx`
    <Button
      variant="${variant}"
      ${disabled ? 'disabled' : ''}
    >
      ${label}
    </Button>
  `,
  // ...
}

Tagged template literals

标签模板字面量

Use the tagged template matching your target language:
TemplateLanguage
figma.tsx
React / JSX / TypeScript
figma.html
HTML / Web Components
figma.swift
Swift
figma.kotlin
Kotlin
figma.code
Generic / fallback
使用与目标语言匹配的标签模板:
模板语言
figma.tsx
React / JSX / TypeScript
figma.html
HTML / Web Components
figma.swift
Swift
figma.kotlin
Kotlin
figma.code
通用/兜底

Step 6: Validate

步骤6:验证

Read back the
.figma.js
file and review it against the following:
  • Property coverage — every Figma property from Step 3 should be accounted for in the template. Flag any that are missing and ask the user if they were intentionally omitted.
  • Rules and Pitfalls — check for the common mistakes listed below (string concatenation of template results, missing
    hasCodeConnect()
    guards, missing
    type === 'INSTANCE'
    checks, etc.)
  • Interpolation wrapping — strings (
    getString
    ,
    getEnum
    ,
    textContent
    ) wrapped in quotes, instance/section values (
    executeTemplate().example
    ) wrapped in braces, booleans using conditionals
  • Tagged template — confirm it matches the project's framework (e.g.
    figma.tsx
    for React, not
    figma.code
    )
If anything looks uncertain, consult api.md for API details and advanced-patterns.md for complex nesting.
重读
.figma.js
文件,对照以下规则检查:
  • 属性覆盖率 —— 步骤3中所有Figma属性都应该在模板中有所体现。标记缺失的属性,询问用户是否是故意省略。
  • 规则与陷阱 —— 检查是否存在下方列出的常见错误(模板结果字符串拼接、缺少
    hasCodeConnect()
    守卫、缺少
    type === 'INSTANCE'
    检查等)。
  • 插值包裹 —— 字符串(
    getString
    getEnum
    textContent
    )用引号包裹,实例/区块值(
    executeTemplate().example
    )用大括号包裹,布尔值使用条件表达式。
  • 标签模板 —— 确认与项目框架匹配(例如React项目用
    figma.tsx
    而非
    figma.code
    )。
如果有不确定的地方,参考api.md查看API详情,参考advanced-patterns.md了解复杂嵌套场景。

Inline Quick Reference

内联速查手册

instance.*
Methods

instance.*
方法

MethodSignatureReturns
getString
(propName: string)
string
getBoolean
(propName: string, mapping?: { true: any, false: any })
boolean | any
getEnum
(propName: string, mapping: { [figmaVal]: codeVal })
any
getInstanceSwap
(propName: string)
InstanceHandle | null
getPropertyValue
(propName: string)
string | boolean
findInstance
(layerName: string, opts?: SelectorOptions)
InstanceHandle | ErrorHandle
findText
(layerName: string, opts?: SelectorOptions)
TextHandle | ErrorHandle
findConnectedInstance
(codeConnectId: string, opts?: SelectorOptions)
InstanceHandle | ErrorHandle
findConnectedInstances
(selector: (node) => boolean, opts?: SelectorOptions)
InstanceHandle[]
findLayers
(selector: (node) => boolean, opts?: SelectorOptions)
(InstanceHandle | TextHandle)[]
方法签名返回值
getString
(propName: string)
string
getBoolean
(propName: string, mapping?: { true: any, false: any })
boolean | any
getEnum
(propName: string, mapping: { [figmaVal]: codeVal })
any
getInstanceSwap
(propName: string)
InstanceHandle | null
getPropertyValue
(propName: string)
string | boolean
findInstance
(layerName: string, opts?: SelectorOptions)
InstanceHandle | ErrorHandle
findText
(layerName: string, opts?: SelectorOptions)
TextHandle | ErrorHandle
findConnectedInstance
(codeConnectId: string, opts?: SelectorOptions)
InstanceHandle | ErrorHandle
findConnectedInstances
(selector: (node) => boolean, opts?: SelectorOptions)
InstanceHandle[]
findLayers
(selector: (node) => boolean, opts?: SelectorOptions)
(InstanceHandle | TextHandle)[]

InstanceHandle Methods

InstanceHandle 方法

MethodReturns
hasCodeConnect()
boolean
executeTemplate()
{ example: ResultSection[], metadata: Metadata }
codeConnectId()
string | null
方法返回值
hasCodeConnect()
boolean
executeTemplate()
{ example: ResultSection[], metadata: Metadata }
codeConnectId()
string | null

TextHandle Properties

TextHandle 属性

PropertyType
.textContent
string
.name
string
属性类型
.textContent
string
.name
string

SelectorOptions

SelectorOptions

ts
{ path?: string[], traverseInstances?: boolean }
ts
{ path?: string[], traverseInstances?: boolean }

Export Structure

导出结构

js
export default {
  example: figma.tsx`...`,                      // Required: ResultSection[]
  id: 'component-name',                         // Required: string
  imports: ['import { X } from "..."'],          // Optional: string[]
  metadata: { nestable: true, props: {} }        // Optional
}
js
export default {
  example: figma.tsx`...`,                      // 必填: ResultSection[]
  id: 'component-name',                         // 必填: string
  imports: ['import { X } from "..."'],          // 可选: string[]
  metadata: { nestable: true, props: {} }        // 可选
}

Tagged Template Types

标签模板类型

TagLanguage
figma.tsx
React / JSX / TypeScript
figma.jsx
React JavaScript
figma.html
HTML / Web Components
figma.swift
Swift
figma.kotlin
Kotlin
figma.code
Generic / fallback
标签语言
figma.tsx
React / JSX / TypeScript
figma.jsx
React JavaScript
figma.html
HTML / Web Components
figma.swift
Swift
figma.kotlin
Kotlin
figma.code
通用/兜底

Rules and Pitfalls

规则与陷阱

  1. Never string-concatenate template results.
    executeTemplate().example
    is a
    ResultSection[]
    object, not a string. Using
    +
    or
    .join()
    produces
    [object Object]
    . Always interpolate inside tagged templates:
    figma.tsx`${snippet1}${snippet2}`
  2. Always check
    hasCodeConnect()
    before
    executeTemplate()
    .
    Calling
    executeTemplate()
    on an instance without Code Connect returns an error section.
  3. Check
    type === 'INSTANCE'
    before calling
    hasCodeConnect()
    .
    findInstance()
    ,
    findConnectedInstance()
    , and
    findText()
    return an
    ErrorHandle
    (truthy, but lacking
    hasCodeConnect()
    ) on failure — not
    null
    . Add a type check to avoid crashes:
    if (child && child.type === 'INSTANCE' && child.hasCodeConnect()) { ... }
  4. Prefer
    getInstanceSwap()
    over
    findInstance()
    when a component property exists for the slot.
    findInstance('Star Icon')
    breaks when the icon is swapped to a different name;
    getInstanceSwap('Icon')
    always works regardless of which instance is in the slot.
  5. Property names are case-sensitive and must exactly match what
    get_context_for_code_connect
    returns.
  6. Use the correct tagged template for the target language (
    figma.tsx
    for React,
    figma.html
    for HTML, etc.). Avoid
    figma.code
    when a specific one is available.
  7. Handle multiple template arrays correctly. When iterating over children, set each result in a separate variable and interpolate them individually — do not use
    .map().join()
    :
    js
    // Wrong:
    items.map(n => n.executeTemplate().example).join('\n')
    
    // Correct — use separate variables:
    const child1 = items[0]?.executeTemplate().example
    const child2 = items[1]?.executeTemplate().example
    export default { example: figma.tsx`${child1}${child2}` }
  1. 永远不要对模板结果进行字符串拼接。
    executeTemplate().example
    ResultSection[]
    对象,不是字符串。使用
    +
    .join()
    会得到
    [object Object]
    。始终在标签模板内部插值:
    figma.tsx`${snippet1}${snippet2}`
  2. 调用
    executeTemplate()
    前必须检查
    hasCodeConnect()
    对没有Code Connect配置的实例调用
    executeTemplate()
    会返回错误区块。
  3. 调用
    hasCodeConnect()
    前必须检查
    type === 'INSTANCE'
    findInstance()
    findConnectedInstance()
    findText()
    执行失败时会返回
    ErrorHandle
    (真值,但没有
    hasCodeConnect()
    方法),而非
    null
    。添加类型检查避免崩溃:
    if (child && child.type === 'INSTANCE' && child.hasCodeConnect()) { ... }
  4. 插槽存在对应组件属性时,优先使用
    getInstanceSwap()
    而非
    findInstance()
    当图标被替换为其他名称时
    findInstance('Star Icon')
    会失效,而
    getInstanceSwap('Icon')
    无论插槽内是哪个实例都能正常工作。
  5. 属性名称区分大小写,必须与
    get_context_for_code_connect
    返回的内容完全一致。
  6. 针对目标语言使用正确的标签模板(React用
    figma.tsx
    ,HTML用
    figma.html
    等)。有对应特定语言的标签时避免使用
    figma.code
  7. 正确处理多个模板数组。 遍历子组件时,将每个结果存到单独变量中分别插值,不要使用
    .map().join()
    js
    // 错误:
    items.map(n => n.executeTemplate().example).join('\n')
    
    // 正确 —— 使用单独变量:
    const child1 = items[0]?.executeTemplate().example
    const child2 = items[1]?.executeTemplate().example
    export default { example: figma.tsx`${child1}${child2}` }

Complete Worked Example

完整示例

Given URL:
https://figma.com/design/abc123/MyFile?node-id=42-100
Step 1: Parse the URL.
  • fileKey
    =
    abc123
  • nodeId
    =
    42-100
    42:100
Step 2: Call
get_code_connect_suggestions
with
fileKey: "abc123"
,
nodeId: "42:100"
,
excludeMappingPrompt: true
. Response returns one component with
mainComponentNodeId: "42:100"
. If the response were empty, stop and inform the user. If multiple components were returned, repeat Steps 3–6 for each.
Step 3: Call
get_context_for_code_connect
with
fileKey: "abc123"
,
nodeId: "42:100"
(from Step 2),
clientFrameworks: ["react"]
,
clientLanguages: ["typescript"]
.
Response includes properties:
  • Label (TEXT)
  • Variant (VARIANT): Primary, Secondary
  • Size (VARIANT): Small, Medium, Large
  • Disabled (BOOLEAN)
  • Has Icon (BOOLEAN)
  • Icon (INSTANCE_SWAP)
Step 4: Search codebase → find
Button
component. Read its source to confirm props:
variant
,
size
,
disabled
,
icon
,
children
. Import path:
"primitives"
.
Step 5: Create
src/figma/primitives/Button.figma.js
:
js
// url=https://figma.com/design/abc123/MyFile?node-id=42-100
// source=src/components/Button.tsx
// component=Button
const figma = require('figma')
const instance = figma.selectedInstance

const label = instance.getString('Label')
const variant = instance.getEnum('Variant', {
  'Primary': 'primary',
  'Secondary': 'secondary',
})
const size = instance.getEnum('Size', {
  'Small': 'sm',
  'Medium': 'md',
  'Large': 'lg',
})
const disabled = instance.getBoolean('Disabled')
const hasIcon = instance.getBoolean('Has Icon')
const icon = hasIcon ? instance.getInstanceSwap('Icon') : null
let iconCode
if (icon && icon.hasCodeConnect()) {
  iconCode = icon.executeTemplate().example
}

export default {
  example: figma.tsx`
    <Button
      variant="${variant}"
      size="${size}"
      ${disabled ? 'disabled' : ''}
      ${iconCode ? figma.tsx`icon={${iconCode}}` : ''}
    >
      ${label}
    </Button>
  `,
  imports: ['import { Button } from "primitives"'],
  id: 'button',
  metadata: { nestable: true }
}
Step 6: Read back file to verify syntax.
给定URL:
https://figma.com/design/abc123/MyFile?node-id=42-100
步骤1: 解析URL。
  • fileKey
    =
    abc123
  • nodeId
    =
    42-100
    42:100
步骤2: 调用
get_code_connect_suggestions
,传入
fileKey: "abc123"
nodeId: "42:100"
excludeMappingPrompt: true
。 响应返回一个组件,
mainComponentNodeId: "42:100"
。如果响应为空,终止操作并告知用户。如果返回多个组件,为每个组件重复步骤3-6。
步骤3: 调用
get_context_for_code_connect
,传入
fileKey: "abc123"
nodeId: "42:100"
(来自步骤2)、
clientFrameworks: ["react"]
clientLanguages: ["typescript"]
响应包含以下属性:
  • Label (TEXT)
  • Variant (VARIANT): Primary, Secondary
  • Size (VARIANT): Small, Medium, Large
  • Disabled (BOOLEAN)
  • Has Icon (BOOLEAN)
  • Icon (INSTANCE_SWAP)
步骤4: 搜索代码库 → 找到
Button
组件。读取源码确认Props:
variant
size
disabled
icon
children
。导入路径:
"primitives"
步骤5: 创建
src/figma/primitives/Button.figma.js
js
// url=https://figma.com/design/abc123/MyFile?node-id=42-100
// source=src/components/Button.tsx
// component=Button
const figma = require('figma')
const instance = figma.selectedInstance

const label = instance.getString('Label')
const variant = instance.getEnum('Variant', {
  'Primary': 'primary',
  'Secondary': 'secondary',
})
const size = instance.getEnum('Size', {
  'Small': 'sm',
  'Medium': 'md',
  'Large': 'lg',
})
const disabled = instance.getBoolean('Disabled')
const hasIcon = instance.getBoolean('Has Icon')
const icon = hasIcon ? instance.getInstanceSwap('Icon') : null
let iconCode
if (icon && icon.hasCodeConnect()) {
  iconCode = icon.executeTemplate().example
}

export default {
  example: figma.tsx`
    <Button
      variant="${variant}"
      size="${size}"
      ${disabled ? 'disabled' : ''}
      ${iconCode ? figma.tsx`icon={${iconCode}}` : ''}
    >
      ${label}
    </Button>
  `,
  imports: ['import { Button } from "primitives"'],
  id: 'button',
  metadata: { nestable: true }
}
步骤6: 重读文件验证语法正确性。

Additional Reference

额外参考

For advanced patterns (multi-level nested components,
findConnectedInstances
filtering, metadata prop passing between parent/child templates):
  • api.md — Full Code Connect API reference
  • advanced-patterns.md — Advanced nesting, metadata props, and descendant patterns
了解高级模式(多级嵌套组件、
findConnectedInstances
筛选、父/子模板间元数据Props传递)可参考:
  • api.md —— 完整的Code Connect API参考
  • advanced-patterns.md —— 高级嵌套、元数据Props和后代查找模式