如何让js2-mode缩进动态匹配flycheck/eslint设置(Emacs 25.2)
动态让js2-mode缩进匹配ESLint配置的方案
嘿,我之前也遇到过这个需求——不想手动同步js2-mode和ESLint的缩进设置,下面几个方法亲测在Emacs 25.2上可行:
方法一:用EditorConfig统一跨工具规则(最省心)
这是我最推荐的方案,EditorConfig能让Emacs、ESLint甚至其他编辑器共享同一套格式规则,完全避免重复配置:
- 在项目根目录新建
.editorconfig文件,把缩进规则和你的ESLint对齐,比如ESLint要求2空格缩进的话:
root = true [*.js] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true
- 给Emacs装
editorconfig包(MELPA里能找到),然后在你的配置里启用它:
(use-package editorconfig :ensure t :config (editorconfig-mode 1))
之后js2-mode会自动读取.editorconfig的设置,覆盖掉js2-mode-js-indent-level的固定值。如果怕ESLint和EditorConfig规则不一致,还可以装eslint-plugin-editorconfig让ESLint直接复用EditorConfig的规则,彻底统一。
方法二:写Elisp函数直接解析ESLint配置
如果你不想额外加EditorConfig,也可以写个小函数,在打开JS文件时自动读取.eslintrc里的缩进规则,动态设置js2-mode的缩进:
(defun my-js2-set-indent-from-eslint () "根据当前项目的ESLint配置设置js2-mode的缩进级别" (interactive) ;; 查找当前目录下的ESLint配置文件 (let* ((eslint-configs '(".eslintrc" ".eslintrc.json" ".eslintrc.js")) (config-file (seq-find #'file-exists-p eslint-configs)) indent-level) (when config-file (with-temp-buffer (insert-file-contents config-file) ;; 匹配JSON格式的indent规则 (when (string-match "\"indent\"\\s-*:\\s-*\\([0-9]+\\)" (buffer-string)) (setq indent-level (string-to-number (match-string 1 (buffer-string))))) ;; 匹配JS格式的indent规则 (when (string-match "indent\\s-*:\\s-*\\([0-9]+\\)" (buffer-string)) (setq indent-level (string-to-number (match-string 1 (buffer-string))))) (when indent-level (setq-local js2-mode-js-indent-level indent-level) (setq-local indent-tabs-mode nil) ; 和ESLint的空格缩进保持一致 (message "从ESLint配置读取缩进级别:%d" indent-level))))) ;; 绑定到js2-mode的启动钩子 (add-hook 'js2-mode-hook #'my-js2-set-indent-from-eslint)
注意:如果你的ESLint配置是通过extends继承的(比如用airbnb的规则),这个简单的正则匹配可能读不到继承后的缩进值,这时候方法一就更靠谱了。
方法三:换用web-mode(原生支持ESLint缩进)
web-mode对JS/JSX的支持很完善,而且原生支持读取ESLint的缩进规则,如果你愿意替换js2-mode的话:
- 安装web-mode,然后配置让JS文件用web-mode打开:
(use-package web-mode :ensure t :config (add-to-list 'auto-mode-alist '("\\.js\\'" . web-mode)) ;; 启用ESLint缩进同步 (setq web-mode-enable-eslint-indentation t))
这样web-mode会自动和ESLint的缩进规则对齐,同时flycheck的eslint检查也能正常工作,省去不少配置麻烦。
内容的提问来源于stack exchange,提问作者haknick
相关产品推荐
相关产品推荐

