Search code examples
typescriptsublimetext3sublimetext

SublimeText Typescript Format on Save


Using Microsoft's Typescript plugin for sublime, I can format a file using ^T ^F as mentioned in features.

Is they a way to run this command automatically when saving a file? I'm after something akin to Sublime-HTMLPrettify Beautify on Save feature.

Thanks.


Solution

  • There is likely an existing plugin on PackgeControl that allows you to do something like this, although I'm not aware of any off the top of my head and the site is not responsive at the moment.

    In the meantime, simplistically you can accomplish this via some simple plugin code:

    import sublime
    import sublime_plugin
    
    class FormatTypescriptOnSave(sublime_plugin.EventListener):
        def on_pre_save(self, view):
            if "TypeScript" in view.settings().get("syntax"):
                view.run_command("typescript_format_document")
    

    To use this, select Tools > Developer > New Plugin... from the menu, then replace the entire contents of the template document with this code, and save it (name doesn't matter, only the extension).

    This catches a save that's about to happen and runs the appropriate command, so long as the current file is a TypeScript file, as determined by the currently set syntax.