# How to Implement Code Connect Templates for Figma Components

> Learn to implement Code Connect templates for Figma components. Map Figma properties to code props using TypeScript files and generate typed snippets efficiently.

- Repository: [OpenAI/plugins](https://github.com/openai/plugins)
- Tags: how-to-guide
- Published: 2026-06-16

---

**Code Connect templates are TypeScript files ([`.figma.ts`](https://github.com/openai/plugins/blob/main/.figma.ts)) that live next to your component source and use the MCP runtime to map Figma properties to code props, generating typed snippets via `figma.selectedInstance` methods.**

The `openai/plugins` repository provides a comprehensive **figma-code-connect** skill that automates the creation of these templates. This guide walks through the implementation workflow defined in [`plugins/figma/skills/figma-code-connect/SKILL.md`](https://github.com/openai/plugins/blob/main/plugins/figma/skills/figma-code-connect/SKILL.md), covering everything from URL parsing to template validation.

## Understanding the Code Connect Architecture

The Code Connect system bridges the gap between Figma designs and production code through a declarative template format. Templates execute within the MCP (Meta-Component Platform) runtime, which exposes a singleton `figma` object containing the currently selected instance.

### The Template Execution Model

When a user selects a Figma component, the runtime populates `figma.selectedInstance`. This object provides type-safe methods to extract property values: `getString` for text, `getBoolean` for toggles, `getEnum` for variants, `getInstanceSwap` for nested components, and `getSlot` for free-form content. The template returns a **`ResultSection[]`** array that the MCP engine stitches into the final code snippet.

### Property-to-Prop Mapping Rules

According to the source specification in [`SKILL.md`](https://github.com/openai/plugins/blob/main/SKILL.md), Figma property types map to specific runtime methods:

- **TEXT** properties use `instance.getString()`
- **BOOLEAN** properties use `instance.getBoolean()` with optional custom value mapping
- **VARIANT** properties use `instance.getEnum()` requiring exhaustive mappings for every enum value
- **INSTANCE_SWAP** properties use `instance.getInstanceSwap()` followed by `executeTemplate()` on the returned instance
- **SLOT** properties use `instance.getSlot()` returning an array of `ResultSection`s for composable content

## Step-by-Step Implementation Workflow

The skill defines a six-stage workflow for creating new Code Connect mappings.

### Step 1: Parse the Figma URL

Extract the `fileKey` and `nodeId` from the Figma component URL, converting hyphens to colons in the node ID. This identifies the specific component instance within the Figma file.

### Step 2: Discover Unmapped Components

Call the MCP tool `get_code_connect_suggestions` with `excludeMappingPrompt:true` to list published components lacking Code Connect mappings. The tool handles three response states: no components available, already mapped components, or a list of candidates requiring templates.

### Step 3: Fetch Component Properties

Use `get_context_for_code_connect` to retrieve the component’s property definitions. This returns typed metadata including TEXT, BOOLEAN, VARIANT, INSTANCE_SWAP, and SLOT definitions that drive the template logic.

### Step 4: Identify the Matching Code Component

Search [`figma.config.json`](https://github.com/openai/plugins/blob/main/figma.config.json) for import paths, then locate a source file whose props interface matches the Figma property list. The skill suggests candidate files and requires user confirmation before proceeding.

### Step 5: Create the [`.figma.ts`](https://github.com/openai/plugins/blob/main/.figma.ts) Template File

Place the template alongside existing templates according to the `include` patterns in [`figma.config.json`](https://github.com/openai/plugins/blob/main/figma.config.json). The file must contain:

- A header comment with the Figma URL
- `source` and `component` metadata declarations
- Necessary imports
- An exported default object with `example`, `imports`, `id`, and optional `metadata`

### Step 6: Validate the Template

Re-read the generated file to ensure every Figma property is covered, types are correct, and no hard-coded children exist. Validation enforces MCP rules: never string-concatenate template results, always check `type === 'INSTANCE'` before calling `executeTemplate()`, and ensure variant mappings are exhaustive.

## Writing the Template Code

Templates use tagged template literals via `figma.code` to generate output. Below are practical implementations based on the references in [`plugins/figma/skills/figma-code-connect/SKILL.md`](https://github.com/openai/plugins/blob/main/plugins/figma/skills/figma-code-connect/SKILL.md).

### Minimal Template Skeleton

```typescript
// url=https://www.figma.com/file/{fileKey}/{fileName}?node-id={nodeId}
// source=src/components/Component.tsx
// component=Component
import figma from 'figma'
const instance = figma.selectedInstance

export default {
  example: figma.code`<Component />`,
  id: 'component-name',
  // optional fields:
  // imports: ['import { Component } from "..."'],
  // metadata: { nestable: true, props: {} },
}

```

### Full-Featured Button Example

```typescript
// url=https://figma.com/design/abc123/MyFile?node-id=42-100
// source=src/components/Button.tsx
// component=Button
import figma from '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.type === 'INSTANCE') {
  iconCode = icon.executeTemplate().example
}

export default {
  example: figma.code`
    <Button
      variant="${variant}"
      size="${size}"
      ${disabled ? 'disabled' : ''}
      ${iconCode ? figma.code`icon={${iconCode}}` : ''}
    >
      ${label}
    </Button>
  `,
  imports: ['import { Button } from "primitives"'],
  id: 'button',
  metadata: { nestable: true },
}

```

## Handling Nested Components and Advanced Patterns

When a component contains configurable child instances not exposed as props, the parent template should discover the child’s own Code Connect template via `getInstanceSwap()` and render it using `executeTemplate()`. This prevents hard-coding and maintains composability.

For complex nesting scenarios, refer to [`plugins/figma/skills/figma-code-connect/references/advanced-patterns.md`](https://github.com/openai/plugins/blob/main/plugins/figma/skills/figma-code-connect/references/advanced-patterns.md), which covers metadata passing and descendant handling strategies.

## Summary

- **Code Connect templates** use the [`.figma.ts`](https://github.com/openai/plugins/blob/main/.figma.ts) extension and live adjacent to component source code
- The **MCP runtime** provides `figma.selectedInstance` with methods like `getString()`, `getEnum()`, and `getInstanceSwap()` to extract Figma properties
- Templates must include a **header comment** with the Figma URL and `source`/`component` metadata
- Always **validate** that `type === 'INSTANCE'` before calling `executeTemplate()` to avoid runtime errors
- Store template locations in **[`figma.config.json`](https://github.com/openai/plugins/blob/main/figma.config.json)** using the `include` array pattern

## Frequently Asked Questions

### What file extension should I use for Code Connect templates?

Code Connect templates must use the [`.figma.ts`](https://github.com/openai/plugins/blob/main/.figma.ts) extension. This convention allows the MCP runtime to identify and execute template files alongside your regular TypeScript source code.

### How do I handle Figma variant properties in the template?

Use `instance.getEnum('PropertyName', { 'FigmaValue': 'codeValue' })` to map variant properties. You must provide an exhaustive mapping object containing every possible variant value from Figma to ensure type safety and complete coverage.

### Where should I place Code Connect templates in my project?

Place templates in the same directory as the component source file they represent, or in directories specified by the `include` patterns in your [`figma.config.json`](https://github.com/openai/plugins/blob/main/figma.config.json) file. The skill automatically checks existing template locations via this configuration before creating new files.

### Can I nest components inside other Code Connect templates?

Yes. Use `getInstanceSwap()` to retrieve child instances, then call `executeTemplate()` on the returned instance after verifying `type === 'INSTANCE'`. This approach discovers the child’s own template definition and maintains composability instead of hard-coding nested markup.