Skip to content

Instantly share code, notes, and snippets.

@zslabs
Forked from steveruizok/getComponents.js
Created April 22, 2022 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zslabs/a9cffc5219591783409a2a6d50a07c4c to your computer and use it in GitHub Desktop.
Save zslabs/a9cffc5219591783409a2a6d50a07c4c to your computer and use it in GitHub Desktop.
Get components and styles (as full nodes) from a Figma file.
async function getComponents(fileKey, token) {
// Get file
const file = await fetch(`https://api.figma.com/v1/files/${fileKey}`, {
headers: { "X-Figma-Token": token }
}).then((r) => r.json())
if (file.err === undefined) {
// Get style ids
const styleIds = Object.keys(file.styles)
// Get component Ids
const componentIds = Object.keys(file.components)
// Get all those Ids together
const ids = [...styleIds, ...componentIds]
// Request all nodes for styles/components
const data = await fetch(
`https://api.figma.com/v1/files/${fileKey}/nodes?ids=${ids}`,
{ headers: { "X-Figma-Token": token } }
).then((d) => d.json())
// Map out style nodes from data using style ids
const styles = styleIds.map((id) => data.nodes[id].document)
// Map out component nodes from data using component ids
const components = componentIds.map((id) => data.nodes[id].document)
return { components, styles, error: "" }
} else {
return { components: [], styles: [], error: file.err }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment