By josh / January 22, 2013

How to automatically run a build when you save a file in Sublime

Last week we talked about creating a custom Sublime Text build system that allows you to run a command line tool or script on demand. That’s convenient, but wouldn’t it be great if your build command ran automatically whenever you modified a file?

Setting this up is simple.

First, install the SublimeOnSaveBuild plugin from Package Control.

Next, make sure Sublime is configured to automatically switch build tools based on the type of file you’re editing by confirming that the Auto option is selected under Tools | Build.

In some situations, this may be all you need to do. If you’re writing CoffeeScript, for example, and you already have the cake tool installed, saving a CoffeeScript file should now trigger a build.

But if you’d like to use a custom build script to perform multiple build steps at once, you’ll need to create a build system in your .sublime-project file.

Here’s an example project file with a custom build_system element that should run any time a file is saved in your project.

This example runs a PowerShell script, build.ps1, that resides in the same directory as the .sublime-project file. This script might perform several steps at once, such as compiling SASS and CoffeeScript files and copying them to a remote test server.

The selector element is key: It determines under what contexts Sublime will run your build script automatically. You’ll need to supply a comma-separated list of Sublime scopes, which are similar to CSS classes. Sublime guesses at the type of code you’re editing based on the file’s name, and then it applies scopes to the various parts of your document. An .html file is scoped as text.html, for example, but a JavaScript snippet inside a .html file is scoped as source.js. I haven’t determined if there’s a scope that applies to every single file type, but using an entry of “source,text” seems to catch everything.

For more tips to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

About the author

josh

Click here to add a comment

Leave a comment: