Emacs: Compile TypeScript File ๐Ÿš€

By Xah Lee. Date: . Last updated: .

Here's a emacs command that compiles the current TypeScript file.

(defvar xah-typescript-compiler
 "tsc"
 "Name or path of TypeScript compiler.
Typically it's \"tsc\".
Used by `xah-typescript-compile-file'.")

(defvar xah-typescript-default-options
"--target ES2017 --alwaysStrict"
 "Default options for TypeScript compiler.
e.g. โ€œ--target ES2017 --alwaysStrictโ€.
Used by `xah-typescript-compile-file'.")

(defun xah-typescript-compile-file ()
  "Compile the current file.
The file name must end in โ€œ.tsโ€ or โ€œ.tsxโ€.
If the file is modified, save it automatically before run.
Depends on `xah-typescript-compiler', `xah-typescript-default-options'.

URL `http://xahlee.info/emacs/emacs/elisp_compile_typescript.html'
Version: 2020-12-13 2022-04-07 2023-08-25 2023-09-19"
  (interactive)
  (let ((resize-mini-windows nil)
        (xOptTemp
         (if current-prefix-arg
             (let ((completion-ignore-case t))
               (completing-read
                "tsc options:"
                '(
                  "None"
                  "Ask"
                  "--target ES5 --alwaysStrict"
                  "--target ES2015 --alwaysStrict"
                  "--target ES2016 --alwaysStrict"
                  "--target ES2017 --alwaysStrict"
                  "--target ES2018 --alwaysStrict"
                  "--target ES2019 --alwaysStrict"
                  "--target ES2020 --alwaysStrict"
                  "--target ES2021 --alwaysStrict"
                  "--target ES2022 --alwaysStrict"
                  ) nil t))
           "--target ES2017 --alwaysStrict"
           ))
        (xoutputb "*typescript compile output*")
        xfname xfExt
        (xprogName xah-typescript-compiler)
        xcmdStr xOptsStr)
    (when (not buffer-file-name) (user-error "Buffer is not file. Save it first."))
    (when (buffer-modified-p) (save-buffer))
    (setq xfname buffer-file-name)
    (setq xfExt (file-name-extension xfname))
    (when (and (not (string-equal xfExt "ts")) (not (string-equal xfExt "tsx")))
      (error "File name ใ€Œ%sใ€ must end in .ts or .tsx" (file-name-nondirectory xfname)))
    (setq xOptsStr
          (let ((x87873
                 (cond
                  ((string-equal xOptTemp "None") "")
                  ((string-equal xOptTemp "Ask")
                   (read-string "tsc option:" xah-typescript-default-options))
                  (t xOptTemp))))
            (if (string-equal xfExt "tsx")
                (concat x87873 " --jsx react ")
              x87873
              )))
    (setq xcmdStr (concat xprogName " " (shell-quote-argument xfname) " " xOptsStr))
    (message "Running ใ€Œ%sใ€" xcmdStr)
    (shell-command xcmdStr xoutputb)))

Emacs, Run Current File