• Hello World

  • Hello World, by Sam Deane — Source code available at GitHub

    This is an extremely simple plugin example, which illustrates how to add a menu command to the Plugins menu and execute some code when it is selected.

  • Layout

    The first thing to do when making a plugin is to setup the folder structure, which should look something like this:

       MyPlugin.sketchplugin/
         Contents/
           Sketch/
             manifest.json
             hello-world.js
    

    Manifest

    The plugin needs a manifest.json file. This tells Sketch which menu items your plugin supplies, as well as giving some general information about the plugin such as its name, author, and so on.

    A single plugin can supply multiple menu items, and each one can execute different code, or they can all share code. In our case though, we just have one command.

    {
        "name" : "Hello World!",
        "identifier" : "com.sketchapp.examples.helloworld",
        "version" : "1.0",
        "description" : "Pretty much the smallest example Sketch Plugin you could have.",
        "authorEmail" : "sam@sketchapp.com",
        "author" : "Sam Deane",
        "commands" : [
        {
          "script" : "hello-world.js",
          "handler" : "onRun",
          "shortcut" : "",
          "name" : "Hello World!",
          "identifier" : "helloworld"
        }
      ]
    }
    
  • Code

    Defining The Run Handler

    In the manifest, we told Sketch that every time the “Hello World!” menu is selected, we want to execute a javascript handler called onRun.

    So now we need to put some code into the hello-world.js file to implement that command.

    function onRun(context) {
  • We are passed a context variable when we’re run. We use this to get hold of a javascript object which we can use in turn to manipulate Sketch.

      var sketch = context.api()
  • Next we want to extract the selected page of the selected (front-most) document

      var document = sketch.selectedDocument
      var page = document.selectedPage
  • Now let’s create a new text layer, using a large font, and a traditional value…

      var layer = page.newText({alignment: NSTextAlignmentCenter, systemFontSize: 36, text:"Hello World"})
  • …resize it so that the text just fits…

      layer.adjustToFit()
  • Finally, lets center the view on our new layer so that we can see where it is.

      document.centerOnLayer(layer)
    };
  • And that’s it. Job done.

    Obviously this is only the tip of the iceberg. Check out some of the other examples to see what else can be done.

    If you have questions, comments or any feedback, ping us at developer@sketchapp.com!

See something wrong or incomplete? Improve this page.