Learn how you can use webpack to set up a Figma plugin project that establishes communication with a React-based UI.
This article will cover how to set up a Figma plugin project with webpack to implement the UI using React. The purpose of the plugin will be to generate three random colors and let the user pick one to assign to a selected element in the Figma document.
This example plugin will demonstrate how to establish communication between the UI and the plugin code, and then how to use the API to achieve the given basic task.
The first thing you’ll need to do is create a Figma plugin through the Figma app. This will generate a template project with a manifest.json
file, which contains the information of your plugin and its ID. In order to create a project, you need to click on the Community section in the left-hand menu, and then, under the Plugins tab, you can find the Create new plugin button.
Once you create your plugin, it will generate all the required files, but in order to integrate TypeScript and Sass compilers and bundle all the assets, such as JavaScript, style files, and possibly SVGs, we need a bundler. For this we will use webpack.
Before configuring webpack, we need some arrangement for the source files. Create a /src
folder and move the ui.html
and code.ts
files in this folder. You can delete the pre-generated code.js
file. Now we need a ui.tsx
file, which will contain the React code written with TypeScript. Create this file under the /src
folder as well.
The last thing we need to do is edit the ui.html
file. This file already contains some HTML and JavaScript, but we only need an HTML element, which will be populated by React. So, replace the entire contents of ui.html
with the following line:
<div id="root"></div>
Eventually, the /src
folder should look like this:
-- src
|- ui.tsx
|- code.ts
|- ui.html
One last thing we need is to configure the manifest.json
file accordingly.
There, you see the main
and ui
keys. These tell Figma where to look for the files containing the plugin code and the UI code, respectively. Since webpack puts the bundled files under the /dist
folder by default, we need to point to specific files under that folder for the main
and ui
keys.
./dist/code.js
is the compiled file from code.ts
, and ./dist/ui.html
is the HTML file that will contain the inline JavaScript code between the <script></script>
tags.
Note that Figma accepts one single file for UI, which means that you cannot have a <script>
tag with src
attribute pointing to a JavaScript file. This is why the ui.html
should contain inline JavaScript code; later, this will be something we specifically tell webpack to do.
{
...
"main": "./dist/code.js",
"ui": "./dist/ui.html"
}
#react #webpack #javascript #web-development #programming