Design tools are constantly improving, and more are entering the market every day (InVision Studio, for example). That being said, modern design tools such as Sketch are created to be minimalistic, where the tool is set out to eliminate all non-essential features. It’s typical to create additional functionality only when needed—and this is where we enter the interesting world of Sketch plugin development.

Developing Sketch plugins can help designers embrace the technical side of how Sketch really works and empower them to automate repetitive tasks. Sketch plugins are made with code and the Sketch JavaScript API, but as designers don’t need to be expert developers in order to use this API, this tutorial demonstrates how to code a plugin to streamline a design process and improve the workflow in Sketch.

Simple but Highly Useful Sketch Plugins

More often than not, Sketch designers have at least three or four Sketch plugins installed. The plugins below are somewhat basic in nature but are commonly used because they’re huge time savers.

If you’re curious to see what can be accomplished with Sketch plugins, take a look at our ultimate list of 50 Sketch plugins.

renameit plugin for sketch

The RenameIt plugin is a popular Sketch plugin that helps designers rename multiple layers at once.

JavaScript Basics in Less Than 2 Minutes

Before you start coding, you’ll need to learn a few things about the JavaScript syntax (that is, the formality of how the code is written). Not only will this help you to write the code for your Sketch plugin, but you’ll better understand how and why the code works.

Comments

Let’s start with code comments.

Code comments are like hidden notes—they’re not user-facing and thus won’t show up in the resulting Sketch plugin. Developers typically use these code comments to explain the code that’s been written, so if another developer reads the code, or if they return to the code later, they’ll understand what’s been written and how it works.

// this is a single-line comment

/*
    This is a 
    multiline comment
*/

Variables

Variables are like little containers that are used to store values; for example:

var firstName = "Manuele Capacci";
// the variable firstName now equals "Manuele Capacci"

To retrieve this value, you need to use the variable; for example:

log(firstName);
// this will record "Manuele Capacci" in the console

sketch plugin development window

The scripting window. Highlighted: the console, which is used for testing the output.

Objects

Objects can store multiple variables, like this:

var user = {
    firstName: "Manuele",
    lastName: "Capacci",
    age: 28,
    role: "Product Designer"
}

Notice that the age value isn’t wrapped in quotes. This is because quotes will define the variable as a string, meaning the intended output is to be literal. We don’t want that; we want the variable to be defined as an integer/number so that we can perform math on it. Putting quotes around the value will undesirably define the value as a string.

We can use the object’s variables, like this:

// using the object's variables
user.firstName;
user.lastName;
user.age;
user.role;

Arrays

Arrays are a simpler type of object:

var users = ["Manuele", "Daniel", "Miklos"]
// "users" is an array that contains a list of names

user[0]; // this equals "Manuele"
user[1]; // this equals "Daniel"
user[2]; // this equals "Miklos"

Functions

Functions are actionable—they do something. In the example below, the function calculates the sum of a and b. In this example, a is 2 and b is 3.

// a function declaration
function sum(a, b) {
    return a + b;
}

// calling the function
sum(2, 3); // this equals 5

// recapping what we've learned so far

var total = sum(2, 3); // the variable "total" will equal 5
log(sum(2, 3)); // this will output 5 in the console
log(total); // this will also output 5 in the console

Conditional Statements

Conditional statements only run the code inside their brackets if the specified condition is met. In the example below, the code runs right away because the value of firstName does in fact equal “Manuele”; therefore, the else if and else code does not run.

var firstName = "Manuele";

if(firstName == "Manuele") {
    // do something for Manuele
} else if(firstName == "Daniel") {
    // do something for Daniel
} else {
    // do something for anybody else
}

Let’s try writing some basic code in Sketch.

Writing Your First Line of Code in Sketch

Navigate to “Plugins → Run Script” in Sketch. In this scripting window, you can write code to make things happen in Sketch (such as rename layers), and later on package this code into a Sketch plugin with the .sketchplugin filetype.

Below: This is what the scripting window looks like the first time you open it. You might see some code that you’re not familiar with, but you’ll learn a little more about JavaScript along the way. The default code that already exists in this window tells you the name of the Sketch document, what layers are currently selected, and more.

accessing the scripting window in sketch

For now, delete all of the code in this window and replace it with:

log("Hello Sketch");

What you’re doing here, is calling the log function and passing the string Hello Sketch as an argument. This log is only accessible behind the scenes, making it useful for debugging code when things aren’t working as expected. If you click the “Run” button, the argument Hello Sketch will be logged in the console underneath the scripting window.

Let’s dig a little deeper.

Creating a Sketch Layer Rename Plugin

Now you can use your knowledge of JavaScript and Sketch scripting to create a script that renames multiple layers at once. Rodrigo Soares created the RenameIt plugin, which accomplishes the same thing and saves designers a lot of time—let’s create a simplified version. Make sure to create some Sketch layers so that you can test your script.

The code must start with a boilerplate line. You need to use Sketch’s Application Programming Interface (API)—this is a fancy term for a special object that you’ll need if you want to interact with Sketch in any meaningful way. Name this special API object sketch.

Obviously, only rename the currently selected layers. How do you find out which layers are currently selected? The Sketch JavaScript API provides a handy way to get this information with just one line of code.

Here’s how to accomplish all of this with JavaScript code:

// assign the API object to a variable
var sketch = context.api();

// assign currently selected layers to a variable
var selection = sketch.selectedDocument.selectedLayers;

All of the information about the currently selected layers is contained inside the selection variable. Now you just need to “iterate” (repeatedly run some code) over the layers to rename them.

For the sake of testing, rename each layer to “Renamed Layer.”

Add this code to the end of your script:

selection.iterate(function(layer) { // for every selected layer
    layer.name = "Renamed Layer"; // rename to "Renamed Layer"
})

Once you hit “Run,” you’ll see that each layer has been renamed to “Renamed Layer,” but so that the user is asked what the new layer name should be. Let’s adapt the script:

// ask the user what the new layer name should be
var newLayerName = context.document.askForUserInput_initialValue('What should these layers be renamed to?', '');

selection.iterate(function(layer) { // for every selected layer
    layer.name = newLayerName; // rename to the value of newLayerName
})

A popup will appear asking the user to specify a new name for the layers.

If you’re not sure how to access certain contexts such as currently selected layers, or how to reveal a user-input box (like in the scenarios above), you can read the official Sketch developer documentation, which will show you what code is required.

When you’re ready to move on, hit the “Save…” button in the bottom-left corner of the scripting window and give the script a name. You’ll now find this Sketch plugin accessible from the Sketch menu under “Plugins,” same as with all other Sketch plugins.

Renaming Layers in Sketch: The Full Code

var sketch = context.api();
var selection = sketch.selectedDocument.selectedLayers;

// ask the user what the new layer name should be
var newLayerName = context.document.askForUserInput_initialValue('What should these layers be renamed to?', '');

selection.iterate(function(layer) { // for every selected layer
    layer.name = newLayerName; // rename to the value of newLayerName
})

Creating a “Select All Layers in a Group” Sketch Plugin

Now let’s create something a little more complex. This next Sketch plugin will auto-select all layers within a group, which you can then adapt to include only text layers, or only shape layers, or it could even auto-detect the layer type and only select layers of that type.

As previously, let’s start by defining the context. Then you can iterate/repeat over the layers within that context and auto-select them.

var sketch = context.api();
var selection = sketch.selectedDocument.selectedLayers;

selection.iterate(function(layer) {
    if(layer.isGroup) { // only run the following code if the selection is a Group
        layer.iterate(function(innerLayer){ // for each layer in the Group
            innerLayer.addToSelection(); // add it to the selection
        });
        layer.deselect(); // deselect the Group, though
    }
});

With this code, all layers within any currently selected groups (providing that some are selected) will be selected. Meanwhile, the groups themselves will be deselected.

To further refine this script, you can include a conditional statement that checks if the layer is of a specific type. Let’s say that you want to specifically select all text layers in a group—to do that, at each iteration, check the layer type of each layer, like so:

if(innerLayer.isText) {
    innerLayer.addToSelection();
}

selecting layers of a specific type in sketch

Select All Text Layers in a Group: The Full Code

var sketch = context.api();
var selection = sketch.selectedDocument.selectedLayers;

selection.iterate(function(layer) {
    if(layer.isGroup) { // only if selection is a Group
        layer.iterate(function(innerLayer){ // for every layer in the Group
            if(innerLayer.isText) { // only if layer is a text layer
                innerLayer.addToSelection(); // add to selection
            }
        });
        layer.deselect(); // deselect the Group, though
    }
});

You can improve this script in various ways, using the documentation as a reference:

  • Enable the user to select shapes only
  • Enable the user to select images only
  • In the event that a group is not selected, automatically select parent group, essentially enabling the user to select layers of a similar type
  • If the group has any nested groups within it, process those the same way

Conclusion

If you’re curious about developing Sketch plugins that other designers can use, take a look at SKPM (Sketch Plugin Manager). SKPM allows designers to package their plugins into the .sketchplugin file format, which makes the plugin installable. During this process, plugin developers are also able to define keyboard shortcuts for the plugin’s actions.

A designer who knows how to code Sketch plugins is a designer that knows how to improve their workflow and work faster when necessary, freeing up more time to spend on delivering a high-quality end product. Not only that, but learning how Sketch works behind the scenes is a terrific opportunity to dive into the world of JavaScript.

Understanding the Basics

What is the use of an if statement?

An "if" statement is a conditional statement that checks if a condition is met before executing the code that follows. If the condition is not met, then the code is not executed.

About the author

Manuele Capacci, Germany
member since November 9, 2015
Manuele is a product design consultant who believes that great attention to user experience and a design thinking approach are the souls of successful projects. He helps entrepreneurs, product owners, and developers all while delighting users, discovering what they want and need, and matching their needs with business objectives. [click to continue...]
Hiring? Meet the Top 10 Freelance Sketch Experts for Hire in November 2018

Comments

comments powered by Disqus
Subscribe
Free email updates
Get the latest content first.
No spam. Just great articles & insights.
Free email updates
Get the latest content first.
Thank you for subscribing!
Check your inbox to confirm subscription. You'll start receiving posts after you confirm.
Trending articles
Relevant Technologies
About the author
Manuele Capacci
Designer
Manuele is a product design consultant who believes that great attention to user experience and a design thinking approach are the souls of successful projects. He helps entrepreneurs, product owners, and developers all while delighting users, discovering what they want and need, and matching their needs with business objectives.