The Sketch JavaScript API is bundled with the Sketch Mac app. To use it, you must require('sketch') before calling any API methods. You can run scripts directly within Sketch via the Plugins › Run Script… panel.
Commonly used modules include Group, Shape, and Rectangle for manipulating the document structure.
// The Sketch JavaScript API is bundled with the Sketch Mac app
// and must be imported before it can be used.
const sketch = require('sketch')
const { Group, Shape, Rectangle } = sketch
// Get the current Document and Page
const doc = sketch.getSelectedDocument()
const page = doc.selectedPage
// Create and select a new Group within the current Page
var group = new Group({
parent: page,
frame: new Rectangle(0, 0, 100, 100),
name: 'Test',
selected: true,
})
// Add a new Rectangle Shape Layer to newly created Group
var rect = new Shape({
parent: group,
frame: new Rectangle(10, 10, 80, 80),
})
// Get and log the current selection
var sel = doc.selectedLayers
console.log(sel.isEmpty)
sel.forEach(function (elem) {
console.log(elem.name)
})