Building a Figma Plugin with React and Webpack
Getting Started
To create a Figma plugin project with React and Webpack, we’ll need to set up a few things. First, create a new Figma plugin through the Figma app, which will generate a template project with a manifest.json
file. This file contains information about your plugin and its ID.
Configuring the Project Structure
Next, create a /src
folder and move the ui.html
and code.ts
files into it. You can delete the pre-generated code.js
file. We’ll also need a ui.tsx
file, which will contain our React code written in TypeScript. Create this file under the /src
folder as well.
Configuring Webpack
To bundle our assets, we’ll need to install some dependencies. Run the following commands to install React, React DOM, Webpack, Webpack CLI, and TypeScript:
npm install react react-dom webpack webpack-cli typescript
Create a webpack.config.js
file in the root directory of your project, and add the following configuration:
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: {
ui: './src/ui.tsx'
},
module: {
rules: [
{
test: /\.tsx$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'ass-loader']
},
{
test: /\.svg$/,
use: ['svg-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/ui.html',
filename: 'ui.html',
inlineSource: '.(js)$'
})
]
};
Setting up the UI
In our ui.tsx
file, we’ll create a React component that generates three random colors and allows the user to select one to assign to a selected element in the Figma document.
Communicating with the Plugin Code
To communicate between the UI and the plugin code, we’ll use a bidirectional messaging system. We can send messages from the UI to the plugin code using the sendMessage
utility function, and listen for messages from the plugin code in the componentDidMount
lifecycle hook.
Using the Figma API
In our code.ts
file, we’ll use the Figma API to detect whether an element is selected in the Figma document and inform the UI accordingly. We’ll also listen for the ASSIGN_COLOR
message from the UI and set the fills property of the selected element to the color sent along with the message.
Putting it all Together
With our project set up, we can now run npm run watch
to build and watch our plugin. Go to Figma, navigate to Plugins > Development, find your plugin, and run it. You should see an empty window. Go back to the same menu and click on Open Console. You should see a test message in the console.
That’s it! You now have a basic Figma plugin set up with React and Webpack. From here, you can explore the Figma API and build more complex plugins to suit your needs.