William Bert

How to use prettier with Emacs js2-mode

 1(require 'nvm)
 2
 3(defun do-nvm-use (version)
 4  (interactive "sVersion: ")
 5  (nvm-use version)
 6  ;; exec-path-from-shell made a new login shell at startup and imported values,
 7  ;; including PATH to exec-path. But nvm-use does setenv "PATH". So we need to
 8  ;; update exec-path to the current PATH in the Emacs process.
 9  (exec-path-from-shell-copy-env "PATH"))
10
11(defun my/use-prettier-if-in-node-modules ()
12  "Use prettier-js-mode if prettier is found in this file's
13project's node_modules. Use the prettier binary from this
14project."
15  (let* ((root (locate-dominating-file
16                (or (buffer-file-name) default-directory)
17                "node_modules"))
18         (prettier (and root
19                      (expand-file-name "node_modules/prettier/bin/prettier.js"
20                                        root))))
21    (when (and prettier (file-executable-p prettier))
22      (setq prettier-js-command prettier)
23      (prettier-js-mode))))
24
25(when (require 'prettier-js nil t)
26  (make-variable-buffer-local 'prettier-js-command)
27  (add-hook 'js2-mode-hook #'my/use-prettier-if-in-node-modules))