当我在Sublime Text中保存eslint
或.js
文件时,是否可以自动运行.jsx
?
我现在正在使用ESLint sublime package,但是每次必须使用Cmd + Option + e
手动运行它。
谢谢!
是的,可以使用一个简单的事件驱动插件来完成,例如我在下面编写的插件。
该插件已经过测试,但是没有使用eslint
命令,因为我不想安装该软件包。显然,可以运行任何命令来代替插件的eslint
行中的view.run_command("eslint")
。如果所需命令使用args,则可以这样指定它们:view.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)
:保存视图后调用。在单独的线程中运行,并且不会阻止应用程序。 [目前在下面的插件中使用。]EventListener
文档is located here-也有加载方法。将插件以.py
扩展名保存在Sublime Text软件包层次结构中的下面。例如~/.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.run_command("eslint")
# Need args? Try this:
# view.run_command("eslint", {"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.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.run_command("eslint")
#
# Run `view.settings().get("syntax")` in the console to get the active syntax path.