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 ((xcmdstr (format "deno fmt --ext %s -" (if Ext Ext "ts")))
        (xoutbuff "*xah-js-format output*")
        (xerrbuff "*xah-js-format error*")
        xoutput
        (shell-command-buffer-name nil))
    ;; 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 xcmdstr xoutbuff nil xerrbuff t)
    (setq xoutput (with-current-buffer xoutbuff (buffer-string)))
    (when (not (string-equal xoutput ""))
      (delete-region Begin End)
      (goto-char Begin)
      (insert xoutput))))

(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 2023-02-07"
  (interactive
   (list
    (progn
      (if buffer-file-name
          buffer-file-name
        (user-error "%s: current buffer must be a file %s" real-this-command (buffer-name)))
      buffer-file-name
      )))
  (shell-command
   (format "deno fmt %s" (shell-quote-argument FileName))))

part of Emacs: Xah JS Mode (JavaScript)

Emacs, Format Code