:::info 📒 本文章基于开发者有一定的前端开发经验,且本地已安装 node、npm、ts、vscode
具体可阅读官网 https://www.figma.com/plugin-docs/setup/

📢 使用到的Figma 版本为 107.1,其他版本步骤可能有所不同 :::

新建

选择 Home -> Plugins -> Manage Plugin -> In development -> New plugin
image.png
输入插件名字,选择插件类型,FigJam 是一个白板软件,咱不需要,直接选 Figma design
image.png
选择插件初始化模板,新手推荐选择UI & API的方便理解
image.png

调试

安装

  1. # 安装依赖
  2. yarn

构建

在 vscode 中打开刚才创建的插件目录,⌘⇧B(Windows 为 Ctrl-Shift-B),监听 code.ts 修改并编译成 code.js
image.png
image.png

运行

回到 Figma,创建一个新设计文件,选择 Plugins -> Development -> [你自己的插件]
image.png
就可以调出模板插件界面啦,这个模板的功能就是你输入几,它创建几个橘色正方形image.png

调试

html更改

例如:修改按钮文案

  1. <h2>Rectangle Creator</h2>
  2. <p>Count: <input id="count" value="5"></p>
  3. <button id="create">创建</button>
  4. <button id="cancel">Cancel</button>
  5. <script>
  6. document.getElementById('create').onclick = () => {
  7. const textbox = document.getElementById('count');
  8. const count = parseInt(textbox.value, 10);
  9. parent.postMessage({ pluginMessage: { type: 'create-rectangles', count } }, '*')
  10. }
  11. document.getElementById('cancel').onclick = () => {
  12. parent.postMessage({ pluginMessage: { type: 'cancel' } }, '*')
  13. }
  14. </script>

需要关闭插件界面,重新打开
image.png

ts更改

例如:修改方块颜色

  1. figma.showUI(__html__);
  2. // Calls to "parent.postMessage" from within the HTML page will trigger this
  3. // callback. The callback will be passed the "pluginMessage" property of the
  4. // posted message.
  5. figma.ui.onmessage = msg => {
  6. // One way of distinguishing between different types of messages sent from
  7. // your HTML page is to use an object with a "type" property like this.
  8. if (msg.type === 'create-rectangles') {
  9. const nodes: SceneNode[] = [];
  10. for (let i = 0; i < msg.count; i++) {
  11. const rect = figma.createRectangle();
  12. rect.x = i * 150;
  13. rect.fills = [{type: 'SOLID', color: {r: 1, g: 0.5, b: 0.5}}];
  14. figma.currentPage.appendChild(rect);
  15. nodes.push(rect);
  16. }
  17. figma.currentPage.selection = nodes;
  18. figma.viewport.scrollAndZoomIntoView(nodes);
  19. }
  20. // Make sure to close the plugin when you're done. Otherwise the plugin will
  21. // keep running, which shows the cancel button at the bottom of the screen.
  22. figma.closePlugin();
  23. };

需要选择 Plugins -> Run last plugin,重新加载
image.png