Inspired by Electron, a simple event emitter you can use to communicate between your main script
and your html
UI. Original by @mattdesl, adapted to TypeScript by me.
Webpack guide for Figma plugins: https://www.figma.com/plugin-docs/bundling-webpack/
Install types for events
:
npm install @types/events
In your script
, i.e. main.ts
:
import { script as io } from './io';
// Show the iframe
figma.showUI(__html__);
io.send('start', { hello: 'world' });
io.once('beep', data => {
console.log('Received', data); // 'boop'
});
And in your ui.ts
import { html as io } from './io';
(async () => {
// Await the first 'start' message
const msg = await io.async('start');
console.log(msg.hello); // 'world'
// Listen for other events
io.on('image-bytes', bytes => decodeBytes(bytes));
// Send data back
io.send('beep', 'boop');
})();
The interface is a Node EventEmitter, so you can use once()
, removeListener
, etc.