Open format: how to read Sketch files and convert to JSON
Learn how to read Sketch files in any operating system using the open format — and extract data such as Color Variables
Last time, we talked about the advantages of using an open file format. Now it’s time to get our hands dirty and do some practical work with Sketch documents. Below, you’ll learn how to extract data — in this example, Color Variables — from the raw file format, which gives you multiple opportunities for automation in your design process.
And automating your design workflow has benefits for everyone involved in the process:
When you automate data extraction from Sketch files, you’ll no longer need to copy colors from your Sketch documents and paste them into a specs document. And you won’t need to remember to run a plugin to sync colors with your handoff tool, either. Which means less bureaucracy, and more design.
Automating data extraction from Sketch files means your design and development teams spend less time wondering if they’re using the same colors, and more time wondering how they can make the product better, faster, or more engaging.
By automating data extraction from Sketch files, you won’t need to spend time learning new tools. Instead, you can get the data you want, in the right format, directly from design files. All you need is some glue code and a CI server — which we’ll cover in more detail in our fifth article of the series.
Requirements
This article is where things start to get more technical. To follow along, you’ll need to be fairly familiar with TypeScript, and have a reasonably recent version of node
installed. For code editing, we recommend Visual Studio Code. You don’t need Sketch or a Mac — you can run the sample code on any operating system.
We’ve created a repository with the code for this article, so you can take a look at the finished project. To keep things short, we’ll only cover the more interesting bits of the code, so please refer to the full project for more implementation details.
You can use the repository as a starting point for your own projects by clicking the ‘Use this template’ button on GitHub’s website.
What we’ll build
In our previous article, we introduced Monday Studio, the fictional company we’ll help with their design and development workflow. Today we’ll build a simple tool to help Monday Studio’s developers:
- Read the colors defined in a Sketch Library
- Create a JSON file they can use directly from Storybook, without them having to open or inspect the Sketch file when someone updates it
- Use the
fromFile
function in the@sketch-hq/sketch-file
package to read the file into memory using aSketchFile
object
SketchFile
object allows us to access the entire document bundle raw data as a JavaScript object. It gives us access to the entire document, including pages, in a single document tree. This differs from the raw JSON data on disk, where each page is its own JSON file.
- Traverse the file contents and extract the relevant data with help from the TypeScript definitions (which will make our work easier by offering us autocomplete for our code)
- Finally, save that data in a format we can use in Storybook.
Reading the Sketch file
const sketchDocumentPath = '../color-library.sketch'
// Load the Sketch document and parse it into a SketchFile object
fromFile(resolve(__dirname, sketchDocumentPath)).then(
(parsedFile: SketchFile) => {
// process the parsed file
}
)
Once we have a SketchFile
object, we’re ready to access the data inside, by using parsedFile.contents.document
. If you’re using Visual Studio Code, the TypeScript definitions will help you search for the right properties:
Parsing data and accessing colors
With the document data already parsed into a convenient TypeScript object, we can access the Color Variables by reading the appropriate attributes. Again, TypeScript definitions will help us discover the right property in the objects we’re working with. But if you still need more information about the objects that make up a Sketch document, you can always turn to the JSON Schemas documented on GitHub.
Checking the schema, we’ll learn that Color Variables are referred to internally as ‘swatches’, and they’re stored in the sharedSwatches
property:
const swatches = document.sharedSwatches.objects.sort((a, b) =>
a.name.localeCompare(b.name, undefined, { numeric: true })
)
While we’re here, we’ll sort the swatches using a neat trick in ECMAScript, the localeCompare
method. When sorting colors you’ll probably find names like colors.brand.green.75
and colors.brand.green.100
. Sorting them alphabetically will place ‘100’ before ‘75’. But the { numeric: true }
option for localCompare
will take care of that and do the right thing with strings containing numbers.
Storing Color Variables as JSON
Color Variables (or swatches, as they’re called here) store color data in RGBA format. We’ll translate that to Hexadecimal for our Storybook JSON using Sindre Sorhus’ fantastic rgb-hex
module.
const colors = {}
swatches.forEach(swatch => {
colors[swatch.name] = rgbHex(
swatch.value.red * 255,
swatch.value.green * 255,
swatch.value.blue * 255,
swatch.value.alpha
)
})
FileFormat.UnitInterval
TypeScript type when working with those.
We’ll store the color information in a JSON file using fs.writeFile
in a colors.json
file. Here’s an excerpt of what it looks like (the HEX is longer than you may typically expect because we’ve included alpha):
{
"Brand/colors.brand.beige.50": "604a1eff",
"Brand/colors.brand.beige.75": "aa8c51ff",
"Brand/colors.brand.beige.100": "e0ca9eff",
"Brand/colors.brand.green.50": "3b5a00ff",
"Brand/colors.brand.green.75": "7b9939ff",
"Brand/colors.brand.green.100": "bbd975ff",
…
}
If you want to see the full output, take a look at the file in the project repository.
Wrap up
You’ve successfully read your first Sketch document using TypeScript and are now ready to automatically extract any information you need from the raw data in a Sketch file.
In the next article, we’ll go a step further and show how you can write to a Sketch document. We’ll do that using the inverse operation to the one we did today — so we’ll read color information from a JSON file and update the Color Variables in a Sketch Library.