prettier-js is a function that formats the current buffer using prettier. The
package also exports a minor mode that applies (prettier-js)
on save.
Ensure that the prettier program is installed:
which prettier
If prettier is not installed already, you can install prettier using npm install -g prettier
or via your package manager.
First require the package:
(require 'prettier-js)
Or use use-package
(available in Emacs 29.1 and above):
(use-package prettier-js)
Then you can hook to your favorite javascript mode:
(add-hook 'js2-mode-hook 'prettier-js-mode)
(add-hook 'web-mode-hook 'prettier-js-mode)
...
To adjust the CLI args used for the prettier command, you can customize the prettier-js-args
variable:
(setq prettier-js-args '(
"--trailing-comma" "all"
"--bracket-spacing" "false"
))
Web-mode is a popular mode for editing .js and .jsx files, but it is used to edit other template files too. If you want to hook prettier-js to web-mode for .js and .jsx files only, you can define a helper function like this:
(defun enable-minor-mode (my-pair)
"Enable minor mode if filename match the regexp. MY-PAIR is a cons cell (regexp . minor-mode)."
(if (buffer-file-name)
(if (string-match (car my-pair) buffer-file-name)
(funcall (cdr my-pair)))))
And then hook to web-mode like this:
(add-hook 'web-mode-hook #'(lambda ()
(enable-minor-mode
'("\\.jsx?\\'" . prettier-js-mode))))
This package requires the diff
tool which is already included on Unix platforms. The simplest way to install diff
on Windows is to use Chocolatey. The steps are as follows:
- Follow the Chocolatey install instructions: https://chocolatey.org/install
- Open an Admin Powershell session
- Install the
diff
program:choco install diffutils
You should now be able to open Emacs and successfully use this package.
On BSD systems (like OpenBSD, FreeBSD), the default diff
program may not support some GNU diff features that prettier-js requires, such as --strip-trailing-cr
. To resolve this:
-
Install GNU diff (often called
gdiff
orgnudiff
):- On OpenBSD:
pkg_add gdiff
- On FreeBSD:
pkg install diffutils
- On OpenBSD:
-
Configure prettier-js to use the GNU diff implementation:
(setq prettier-js-diff-command "gdiff")
(Use the appropriate command name for your system, which might be
gdiff
,gnudiff
, orgd
)
This package is customizable via custom.el:
M-x customize-group prettier-js
prettier-js-command
is the prettier commandprettier-js-args
are the args passed to the prettier commandprettier-js-use-modules-bin
enables use ofnode_modules/.bin/prettier
(your project's prettier version)prettier-js-show-errors
customizes where to display the error output (buffer, echo or nil)prettier-js-width-mode
customizes the width when formatting buffer contents (window, fill or nil)