Next: , Up: Setting up Emacs for JavaScript   [Index]


13.8.1.1 Part 1

  1. JS Mode

    Emacs comes with a major mode for JavaScript named js-mode.

    We’ll be using js2-mode instead, an external package that extends js-mode and provides a very interesting feature: instead of using regular expressions, it parses buffers and builds an AST for things like syntax highlighting. While diverging a bit from the traditional “Emacs way of doing things”, this is really interesting, and used as the foundation for other features like refactorings.

  2. JS2 Mode
    1. Setting Up JS2 Mode
      • install and setup js2-mode like the following:
        M-x package-install RET js2-mode RET
        
        (require 'js2-mode)
        (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
        
        ;; Better imenu
        (add-hook 'js2-mode-hook #'js2-imenu-extras-mode)
        
  3. JS2 Refactor

    js2-refactor is a JavaScript refactoring library for emacs. js2-refactor adds powerful refactorings based on the AST generated by js2-mode. It provides a collection of refactoring functions leveraging the AST provided by js2-mode.

    M-x package-install RET js2-refactor RET
    

    Refactorings go from inlining/extracting variables to converting ternary operators to ‘if’ statements. The ‘README’ provides the full list of keybindings.

    One minor tweak that I really couldn’t live without is binding js2r-kill to ‘C-k’ in JS buffers:

    (define-key js2-mode-map (kbd "C-k") #'js2r-kill)
    

    This command is very similar to killing in paredit: It kills up to the end of the line, but always keeping the AST valid.

  4. Xref JS2

    xref-js2 makes it easy to jump to function references or definitions. xref-js2 adds support for quickly jumping to function definitions or references to JavaScript projects in Emacs (>= 25.1).

    xref-js2 uses ag to perform searches, so you’ll need to install it as well. Instead of using a tag system, it relies on ag to query the codebase of a project.

    M-x package-install RET xref-js2 RET
    
    M-.

    Jump to definition

    M-?

    Jump to references

    M-,

    Pop back to where M-. was last invoked.

    (require 'js2-refactor)
    (require 'xref-js2)
    
    (add-hook 'js2-mode-hook #'js2-refactor-mode)
    (js2r-add-keybindings-with-prefix "C-c C-r")
    (define-key js2-mode-map (kbd "C-k") #'js2r-kill)
    
    ;; js-mode (which js2 is based on) binds "M-." which conflicts with xref, so
    ;; unbind it.
    (define-key js-mode-map (kbd "M-.") nil)
    
    (add-hook 'js2-mode-hook (lambda ()
      (add-hook 'xref-backend-functions #'xref-js2-xref-backend nil t)))
    
  5. Summary

    We still have a lot to explore like linting, getting good auto-completion, using snippets, setting up a REPL and debugger, etc.


Next: Part 2, Up: Setting up Emacs for JavaScript   [Index]