Yes, you can turn custom code into a Figma plugin. This guide covers the technical steps to write code, package it for Figma, and deploy it as a plugin—no prior plugin experience needed. You’ll need JavaScript (or TypeScript) and a Figma Developer API understanding, but the actual build process is straightforward once the structure is set up.

What You'll Need

  • A code editor (VS Code, WebStorm, or Sublime Text) with JavaScript/TypeScript support.
  • Figma account with developer access (free tier works).
  • Basic knowledge of JavaScript (ES6+) or TypeScript for plugin logic.
  • The Figma Developer Platform API documentation open in a tab.
  • Node.js and npm installed (for local testing).
  • A Figma Developer Dashboard account (free).

Step-by-Step

  1. Set Up Your Project Structure Create a new folder for your plugin. Inside, add these files:
    • manifest.json (plugin metadata and permissions).
    • src/index.ts (or index.js for JS) for your plugin logic.
    • figma-plugin.zip (generated later for upload).
    Example manifest.json:
        {
          "name": "My Custom Plugin",
          "id": "123456789012345678", // Random 16-digit ID (generate via Figma Dev Dashboard)
          "api": "1.0.0",
          "main": "src/index.ts",
          "host": "figma",
          "background": "none",
          "permissions": ["layers", "nodes"]
        }
        
  2. Write Your Plugin Logic In src/index.ts, use the Figma API to interact with the canvas. Example: a basic "duplicate selected layers" function:
        import { nodes } from "figma";
    
        async function duplicateSelected() {
          const selected = figma.currentPage.selection;
          if (selected.length === 0) return alert("No layers selected!");
    
          selected.forEach((layer) => {
            const duplicate = layer.duplicate();
            duplicate.setPosition(
              layer.position.x + 100,
              layer.position.y + 100
            );
          });
        }
    
        duplicateSelected();
        
    Key notes:
    • Use figma.api for design manipulation (e.g., nodes, layers).
    • Async functions are required for most operations (Figma API calls).
    • Test with console.log—errors appear in Figma’s plugin console (View > Developer > Show Plugin Console).
  3. Add TypeScript Support (Optional but Recommended) Install dependencies:
        npm init -y
        npm install typescript @types/figma --save-dev
        
    Add a tsconfig.json:
        {
          "compilerOptions": {
            "target": "ES6",
            "module": "ESNext",
            "outDir": "./dist",
            "strict": true,
            "esModuleInterop": true
          }
        }
        
    Compile with:
        npx tsc
        
    This generates dist/index.js—update manifest.json to point to this file if using TypeScript.
  4. Test Locally with Figma
    1. Open Figma and go to File > Open Plugin Manager (or View > Developer > Open Plugin Manager on desktop).
    2. Click Install Plugin and select your dist/index.js (or src/index.js if not using TS).
    3. Run your plugin via the Actions dropdown in the top bar. Test edge cases (e.g., no selection, multiple layers).
  5. Package for Distribution Zip your plugin folder (excluding node_modules and .git if present). Rename the ZIP to figma-plugin.zip.
        zip -r figma-plugin.zip . -x "node_modules/*" "*.git/*"
        
    (Linux/macOS; Windows users use 7-Zip or WinRAR.)
  6. Publish to the Figma Community
    1. Go to the Figma Developer Dashboard.
    2. Click Upload Plugin and drag your figma-plugin.zip file.
    3. Fill in metadata (description, tags, icon). Note:
      • Icons must be 512×512 PNG (Figma provides templates).
      • Permissions must match your code’s needs (e.g., "layers" for layer manipulation).
    4. Submit for review (Figma approves plugins within 1–3 days).
  7. Distribute Your Plugin After approval, your plugin appears in: Users install via File > Open Plugin Manager or directly from your link.

Common Mistakes

  1. Overlooking API Permissions

    Requesting unnecessary permissions (e.g., "storage" when you only need "layers") can block plugin submission. Review the permissions docs to scope your access.

  2. Ignoring Figma’s Sandbox Environment

    Plugins run in a secure sandbox. Attempting to access external APIs (e.g., fetch data from a server) will fail unless you use Figma Webhooks (for server-side logic).

  3. Hardcoding IDs

    Instead of:

        const myLayer = figma.getNodeById("12345");
        
    Use relative selection or dynamic queries (e.g., figma.currentPage.selection). Hardcoded IDs break if the design changes.

  4. Not Testing Error States

    Always handle cases like:

    • No layers selected.
    • Invalid node types (e.g., trying to duplicate a text node as a shape).
    • Permission denied (e.g., trying to edit locked layers).
    Example:
        try {
          duplicateSelected();
        } catch (error) {
          figma.notify(error.message);
        }
        

Tips

  1. Use Figma’s Plugin API Explorer Test API calls interactively via View > Developer > Open Plugin API Explorer. This helps debug edge cases before writing code.
  2. Leverage Figma Events Extend plugins with on("selectionchange") or on("layerAdded") to react to user actions dynamically:
        figma.ui.onmessage = (msg) => {
          if (msg.type === "UPDATE_LAYERS") {
            updateLayerPositions();
          }
        };
        
  3. Optimize for Performance Avoid long-running loops in the main thread. Use figma.finish() to pause execution and allow UI responsiveness:
        figma.finish("Processing..."); // Show progress dialog
        setTimeout(() => {
          figma.finish("Done!"); // Close dialog
        }, 1000);
        
  4. Localize Your Plugin Use Figma’s i18n system for translations. Add a locales key to manifest.json:
        "locales": {
          "en-US": {
            "name": "My Plugin",
            "description": "Duplicate selected layers..."
          }
        }
        
    Access translations via figma.locales in your code.
  5. Publish Early, Iterate Start with a minimal plugin (e.g., a single utility function) and expand features. Use the Figma Testing Mode to gather feedback from beta users before full submission.

Troubleshooting

Plugin Won’t Load in Figma

  1. Check the Plugin Console Open View > Developer > Show Plugin Console to see errors. Common issues:
    • ReferenceError: figma is not defined → Your code isn’t compiled or the manifest points to the wrong file.
    • TypeError: Cannot read property 'selection' of null → No layers are selected (add validation).
  2. Verify Manifest Validity Use Figma’s manifest validator to check for syntax errors.
  3. Clear Cache In Figma, go to Edit > Preferences > Plugins and click Clear Cache. Restart Figma.

Plugin Crashes or Freezes

  1. Long-Running Operations If your plugin hangs, break work into chunks or use figma.finish() to yield control. Example:
        const items = figma.currentPage.selection;
        for (let i = 0; i < items.length; i++) {
          figma.finish(`Processing ${i + 1}/${items.length} layers...`);
          const duplicate = items[i].duplicate();
          // ... modify duplicate
        }
        figma.finish("Complete!");
        
  2. Check for Infinite Loops Debug with console.log to trace execution. Tools like Figma Debugger (Chrome extension) help visualize plugin flow.

Plugin Rejected by Figma

  1. Review Rejection Reasons Figma provides feedback via email or the Dashboard. Common reasons:
    • Unnecessary permissions → Scope down your permissions array.
    • Malicious behavior → Avoid altering system files or accessing external APIs without Webhooks.
    • Poor UX → Ensure your plugin doesn’t block Figma’s UI or requires user input without guidance.
  2. Resubmit with Fixes Address each issue in your updated ZIP file. For example, if rejected for "missing description," add one to manifest.json.

Users Can’t Install the Plugin

  1. Check Plugin Visibility Ensure your plugin is set to Public in the Dashboard (default). Private plugins require sharing a direct link.
  2. Verify Plugin ID The id in manifest.json must match the one generated in the Dashboard. Regenerate if needed.
  3. Test Installation Steps Have a colleague (or yourself) follow these steps:
    1. Open Figma.
    2. Go to File > Open Plugin Manager.
    3. Search for your plugin name or use the direct link.
    If it fails, check for:
    • Network errors (try a different browser).
    • Corrupted ZIP file (re-upload).

Frequently Asked Questions

Can I use external libraries in my Figma plugin?

No. Figma plugins run in a sandbox and cannot import external npm packages (except those bundled by Figma, like @figma/api). Stick to vanilla JS/TS or Figma’s built-in APIs.

How do I update an existing plugin?

Submit a new ZIP file via the Dashboard. Figma will prompt you to update the existing listing. Users will see the update automatically after approval (usually within 24 hours).

Is there a way to test plugins without publishing?

Yes! Use Figma’s Testing Mode. After uploading a ZIP, select "Test" in the Dashboard to generate a shareable link. Collaborators can test without public exposure.

Can I monetize a Figma plugin?

Figma allows monetization via paid plugins (one-time purchase or subscription). Set up pricing in the Dashboard under "Pricing." Note:

  • Paid plugins must provide a free trial or demo.
  • Figma takes a 30% cut of revenue.

What’s the difference between a plugin and a Figma API script?

Plugins are reusable tools installed via the Plugin Manager, while Figma API scripts are one-off scripts run directly in the Plugin API Explorer (no installation needed). Plugins persist across projects; scripts are ephemeral.

How do I debug a plugin that runs but produces no output?

Use figma.notify() to show messages in Figma’s UI:

figma.notify("Debug: Layer count = " + figma.currentPage.selection.length);
For deeper debugging, log to the console:
console.log("Debug: ", { selection: figma.currentPage.selection });
Open the console via View > Developer > Show Plugin Console.

Can I access Figma’s cloud files programmatically?

No. Plugins cannot directly read/write cloud files. Use Webhooks to trigger actions server-side when events occur (e.g., file updates). For file access, consider the Figma Design Studio API (for developers).