首页 > 解决方案 > 在 Sublime Text 中保存时自动运行命令

问题描述

eslint当我在 Sublime Text 中保存文件.js或文件时,是否可以自动运行?.jsx

我现在正在使用ESLint sublime 包,但每次使用Cmd + Option + e.

谢谢!

标签: sublimetext3sublimetextsublime-text-pluginsublimelinter

解决方案


是的,这可以通过一个简单的事件驱动插件来完成,就像我在下面写的那样。

该插件已经过测试,但没有使用eslint命令测试,因为我不想安装该软件包。显然,任何命令都可以运行而不是eslint在插件的run_command("eslint")行中。如果所需的命令采用 args,则可以像这样指定它们:run_command("command", {"arg_1": val, "arg_2": val}).

on_post_save_async(self, view)方法(在我下面的插件中)将在view保存后调用,即活动缓冲区 - 请注意,这包括自动保存。on_post_save_async()在单独的线程中运行并且不会阻塞应用程序。您可以更改插件以使用类似的方法,具体取决于您是要eslint在文件保存之前还是之后调用,以及该方法是应该阻塞应用程序还是在其自己的非阻塞线程中运行。以下是 4 个备选方案:

  • on_pre_save(self, view):在保存视图之前调用。它阻塞应用程序,直到方法返回。
  • on_pre_save_async(self, view):在保存视图之前调用。在单独的线程中运行,并且不会阻塞应用程序。
  • on_post_save(self, view): 保存视图后调用。它阻塞应用程序,直到方法返回。
  • on_post_save_async(self, view): 保存视图后调用。在单独的线程中运行,并且不会阻塞应用程序。[目前在下面的插件中使用。]
  • Sublime TextEventListener文档位于此处- 也有加载方法。

将插件保存在 Sublime Text 包层次结构中的某个位置,并带有.py扩展名。例如~/.config/sublime-text-3/Packages/User/AutoRunESLintOnSave.py,它应该立即工作。

import sublime, sublime_plugin

class AutoRunESLintOnSave(sublime_plugin.EventListener):
    """ A class to listen for events triggered by ST. """

    def on_post_save_async(self, view):
        """
        This is called after a view has been saved. It runs in a separate thread
        and does not block the application.
        """

        file_path = view.file_name()
        if not file_path:
            return
        NOT_FOUND = -1
        pos_dot = file_path.rfind(".")
        if pos_dot == NOT_FOUND:
            return
        file_extension = file_path[pos_dot:]
        if file_extension.lower() in [".js", ".jsx"]:
            view.window().run_command("eslint")

            # Slight variations are needed for an ApplicationCommand,
            # a WindowCommand, or a TextCommand.
            #
            # view.run_command("text_command")
            # view.window().run_command("window_command")
            # sublime.run_command("application_command")
            #
            # Need args? Use this:
            #
            # view.run_command("command", {"arg_1": val, "arg_2": val})

您可以使用缓冲区的语法,而不是使用文件扩展名来触发运行eslint命令,代码更加简洁。

    def on_post_save_async(self, view):
        """ Syntax version. """

        current_syntax = view.settings().get("syntax")
        if ("JavaScript.sublime-syntax" in current_syntax
                or "JSX.sublime-syntax" in current_syntax):
            view.window().run_command("eslint")

        # You could, of course, use an exact match:
        #
        # current_syntax = view.settings().get("syntax")
        # if current_syntax == "Packages/JavaScript/JavaScript.sublime-syntax":
        #     view.window().run_command("eslint")
        #
        # Run `view.settings().get("syntax")` in the console for the active syntax path.

推荐阅读