Emacs: Compile TypeScript File

By Xah Lee. Date: . Last updated: .

Here's a emacs command that compiles the current TypeScript 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 2021-07-31 2022-03-26 2022-04-07"
  (interactive)
  (let ((resize-mini-windows nil)
        (xOptTemp
         (if current-prefix-arg
             (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"
                ))
           "--target ES2017 --alwaysStrict"
           ))
        ($outputb "*typescript compile output*")
        $fname $fExt
        ($progName xah-typescript-compiler)
        $cmdStr xOptsStr)
    (when (not (buffer-file-name)) (save-buffer))
    (when (buffer-modified-p) (save-buffer))
    (setq $fname (buffer-file-name))
    (setq $fExt (file-name-extension $fname))
    (when (and (not (string-equal $fExt "ts")) (not (string-equal $fExt "tsx")))
      (error "File name 「%s」 must end in .ts or .tsx" (file-name-nondirectory $fname)))
    (setq xOptsStr
          (let ((x87873
                 (cond
                  ((string-equal xOptTemp "None") "")
                  ((string-equal xOptTemp "Ask")
                   (read-string "tsc option:" xah-typescript-default-options))
                  (t xOptTemp))))
            (if (equal $fExt "tsx")
                (concat x87873 " --jsx react ")
              x87873
              )))
    (setq $cmdStr (concat $progName " " (shell-quote-argument $fname) " " xOptsStr))
    (message "Runing 「%s」" $cmdStr)
    (shell-command $cmdStr $outputb)))

See also: Emacs: Run Current File 🚀

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial