Frontend Quick Tips #14 Sync Your Icons With Figma API
Those may be some patterns explained in JS code on real-life examples or some techniques for better code.
Problem
Adding or editing assets often requires two people to make the change: a designer and a developer. They have to sync after every update, which is often quick but interrupts other work.
Solution
The Figma API makes it possible to extract almost any data from design files into your project.
One obvious integration many projects can benefit from is syncing your svg files with Figma. I will use figma-api-exporter, it is still an early version, but it was already tested in production. Feel free to contribute.
Requirements
- Figma Access Token - follow the instruction
- Figma File with icons changed to components
Downloading icons as svgs
const figmaApiExporter = require('figma-api-exporter').default;
const exporter = figmaApiExporter(YOUR_ACCESS_TOKEN);
exporter
.getSvgs({
fileId: FIGMA_FILE_ID,
canvas: 'Icons',
})
.then(async svgsData => {
await exporter.downloadSvgs({
saveDirectory: './figmaIcons',
svgsData: svgsData.svgs,
lastModified: svgsData.lastModified,
clearDirectory: true,
});
});
Save it as YOUR_NAME.js
file and run it with node YOUR_NAME.js
. You should see files appearing in the figmaIcons
directory.
Displaying all available icons (ex. in Storybook)
By default there is no easy way to import all files from a directory. However, you can use create-index to generate an index.js
file with files exported as modules after every sync.
const { writeIndex } = require('create-index');
const path = require('path');
...
await exporter.downloadSvgs(...)
writeIndex([path.join(__dirname, './figmaIcons')], {
update: true,
extensions: ['svg'],
});
index.js
will look like this:
export { default as TAB } from './TAB.svg';
export { default as Three } from './Three.svg';
export { default as TrackingSurveys } from './TrackingSurveys.svg';
Then in Storybook you can import all svg files and iterate over them:
import * as allSvgIcons from './figmaIcons';
Making it work in production
Option 1: Plug it into CI
Make your script run on every deployment. Every deployment will update the icons to the latest version. The downside is increased build time.
Option 2: Sync and push
If you are concerned about your deployment time, you can run the script locally and push new/updated files to the repository. It is a less preferred option, as it removes most of the automation. You still have to perform some actions after the designer updates the icons.