Emacs: Format JavaScript Code 🚀

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defun xah-js-format-region (Begin End &optional Ext)
  "Format code of current region.
Code can be JavaScript, TypeScript, JSON, Markdown, etc.
This command requires command line tool deno.

Ext is filename extension sans the period. Default to js.
 (as of 2022-09-25, valid values are js ts jsx tsx md markdown json jsonc)

URL `http://xahlee.info/emacs/emacs/emacs_format_js_code.html'
Version: 2022-08-28 2022-09-25 2022-10-28 2023-01-13"
  (interactive "r")
  (let (($cmdstr (format "deno fmt --ext %s -" (if Ext Ext "ts")))
        ($outbuff "*xah-js-format output*")
        ($errbuff "*xah-js-format error*")
        $output)
    ;; not replacing region cuz when there's error, the stdout is empty. so, we need to check the stdout
    (shell-command-on-region Begin End $cmdstr $outbuff nil $errbuff t)
    (setq $output (with-current-buffer $outbuff (buffer-string)))
    (when (not (string-equal $output ""))
      (delete-region Begin End)
      (goto-char Begin)
      (insert $output))))

(defun xah-js-format-buffer ()
  "Format JavaScript/TypeScript code of current buffer.
If buffer is a file, it is saved first.
This command requires command line tool deno.

URL `http://xahlee.info/emacs/emacs/emacs_format_js_code.html'
Version: 2020-09-23 2022-03-13 2022-06-14 2022-08-28 2022-09-25 2022-10-28"
  (interactive)
  (if buffer-file-name
      (progn
        (save-buffer)
        (xah-js-format-file buffer-file-name)
        (revert-buffer t t t))
    (xah-js-format-region (point-min) (point-max))))

(defun xah-js-format-file (FileName)
  "Format JavaScript/TypeScript code of file.
When called interactively, the file is the current buffer file.
This command requires command line tool deno.

URL `http://xahlee.info/emacs/emacs/emacs_format_js_code.html'
Version: 2022-08-28"
  (interactive
   (list
    (let ((xfpath (buffer-file-name)))
      (when (not xfpath)
        (user-error "%s: current buffer must be a file %s" real-this-command (buffer-name)))
      xfpath
      )))
  (shell-command
   (format "deno fmt %s" (shell-quote-argument FileName))))

part of Emacs: Xah JavaScript Mode (xah-js-mode.el)

Emacs, Format Code