Turbocharge VS Code for Angular Development

I like using Visual Studio Code for my Angular development, because it is TypeScript-friendly, supports in-editor Chrome Debugging, and has numerous extensions for boosting productivity.  In this post I’d like to show how you can turbocharge VS Code to make it an even more powerful tool for developing Angular applications.

angular-ts-code

Tasks and Keyboard Shorcuts

Nowadays the best way to build an Angular app is using Angular CLI.  Not only can you use it to scaffold a new app and to generate modules, components and services, but there are commands you use all the time for linting, building, and serving the app, as well as running unit and end-to-end tests.  That usually means having to toggle back and forth between Visual Studio Code and the Terminal.

Get the code this this blog post here: https://github.com/tonysneed/vscode-ng

The integrated terminal in Visual Studio Code allows you do this from within the editor, but you still have to type all your commands into the terminal window and manually create new windows to run multiple commands simulataneously.

vs-code-terminal.png

It would be a big time-saver if you could use keyboard shortcuts to execute the npm scripts for Angular in package.json.  Here are scripts added by Angular CLI when you create a new application.

{
  "name": "my-dream-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

You should generally run “npm start” rather than “ng serve,” because the npm script will use the version of @angular/cli that is exactly specified in project.json, whereas “ng serve” uses the CLI version that is installed globally and is frequently updated.  If you use the local CLI version, then your app should be insulated from dependencies may change when the global CLI is updated.

The way to do this is first to create tasks in VS Code that execute these scripts.  Then you can assign keyboard shortcuts to run each task.  Version 2.0.0 of the tasks.json schema is more flexible and powerful than the prior version.  For example, you can define tasks that natively run npm scripts.  The “build” and “test” scripts are good candidates for this because they are natively mapped by VS Code to standard key bindings (Shift+Cmd+B and Shift+Cmd+T respectively).

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "npm",
            "script": "build",
            "presentation": {
                "reveal": "always"
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": [
                "$tsc"
            ]
        },
        {
            "label": "test",
            "type": "npm",
            "script": "test",
            "presentation": {
                "reveal": "always"
            },
            "group": {
                "kind": "test",
                "isDefault": true
            }
        },

However, to assign keyboard shortcuts to other tasks, you need to use the “shell” type to specify a task name, which is required in order to assign a keyboard shortcut.  Note that “args” has been deprecated, so you need to concatenate arguments to the “command” string.  NPM scripts accept parameters if you preceed them with a double hyphens.  For example, you can use this approach to pass an “-o” argument, so that the app is opened in a browser when it is served.

{
    "taskName": "serve",
    "type": "shell",
    "command": "npm start",
    "problemMatcher": [
        "$tsc"
    ]
},
{
    "taskName": "open",
    "type": "shell",
    "command": "npm start -- -o",
    "problemMatcher": [
        "$tsc"
    ]
},
{
    "taskName": "lint",
    "type": "shell",
    "command": "npm run lint",
    "problemMatcher": [
        "$tsc"
    ]
},
{
    "taskName": "e2e",
    "type": "shell",
    "command": "npm run e2e"
}

Here are shortcuts you can paste into your keybindings.json file.  Note the shortcut to terminate a running task by pressing Shift+Cmd+X.  If you run multiple tasks at the same time, you will be prompted to select which task you want to end.  Also note I assigned Shift+Cmd+O to opening the app, so the shortcut for “Go to Symbol” needs to be assigned to another shortcut (Ctrl+Shift+O).

// Place your key bindings in this file to overwrite the defaults
[
    // End a running background task
    {
        "key": "shift+cmd+x",
        "command": "workbench.action.tasks.terminate"
    },
    // Show Source Control
    {
        "key": "shift+cmd+g",
        "command": "workbench.view.scm"
    },
    {
        "key": "ctrl+shift+g",
        "command": "-workbench.view.scm"
    },
    // Lint
    {
        "key": "ctrl+shift+l",
        "command": "workbench.action.tasks.runTask",
        "args": "lint"
    },
    // Tests
    {
        "key": "shift+cmd+t",
        "command": "workbench.action.tasks.test"
    },
    // E2E Tests
    {
        "key": "ctrl+shift+e",
        "command": "workbench.action.tasks.runTask",
        "args": "e2e"
    },
    // Serve app
    {
        "key": "shift+cmd+s",
        "command": "workbench.action.tasks.runTask",
        "args": "serve"
    },
    // Open app
    {
        "key": "shift+cmd+o",
        "command": "workbench.action.tasks.runTask",
        "args": "open"
    },
    // Go to symbol (remapped)
    {
        "key": "ctrl+shift+o",
        "command": "workbench.action.gotoSymbol"
    }
]

Now you can lint, build, serve, open and test your Angular app simply by pressing a few keyboard shortcuts.  Each task will execute in its own terminal window, so you can run them simulateously.  Here is a demo of pressing Shift+Cmd+S to execute “ng serve” via “npm start.”

ng-serve-all.gif

Here is a demo of pressing Shift+Cmd+T to execute “ng test” via “npm run test.”

ng-test-all

Extensions

The first extension I’ll recommend for Angular development with VS Code is a file icon theme called vs-code-icons.  Its bright colors make working with the Explorer pane a pleasure.

There are certain chores that are tedious and error-prone.  One of those is adding and managing imports.  While VS Code can add imports via the “quick fix” (a.k.a. light bulb) menu, it will use double quotes, which will have to be changed later to single quotes (in compliance with the default Typescript linting rules), and it won’t care about the order of the import statements, or clean up imports that are no longer used.

ts-hero.png

The best way out of this quagmire is to install a VC Code extension called TypeScript Hero.  When you install it, you’ll get commands on the quick fix menu for adding imports, as well as keyboard shorcuts for managing imports.  My favorite is Ctrl+Opt+O, which organizes imports by sorting them according to convention and removing imports that are unused.  You can see which commands and shortcuts are available by opening the Command Palette (Shift+Cmd+P) and entering “TS Hero.”  All the commands are documented on the project home page.

Another thing that can mess you up is when you have to rename or move files and folders, which breaks imports for those files.  This is where an extension called Move TS can be a life saver.  To use it simply right-click on a file or folder in the Explorer pane and select “Move TypeScript.”

move-ts.gif

Two more essential extensions are TSLint, which provides real-time linting of TypeScript files in VS Code, and the Angular Language Service, which give you things like intellisense and Cmd+click go-to-definition inside of HTML template files.

ng-lang.gif

There are a few other miscellaneous extensions that I like.  If you’re editing markdown a lot, I recommend Markdown Shortcuts, which lets you create a code block by pressing Ctrl+M, Ctrl+C.  You also get an icon to open markdown preview to the side.

md-preview-before

Before

md-preview-after

After

For enhanced version control in the Editor, I recommend the Git History extension for comparing different file version in the git log, and Open in GitHub for jumping to a file in a remote repository — Bitbucket, Gitlab and VisualStudio.com are also supported.

git-history.gif

Chrome Debugging

Last but not least, one of the killer features of VS Code is support for debugging, and the Debugger for Chrome extension lets you set breakpoints and step through code in an Angular app without having to leave the comfort of the VS Code editor.  Start by adding the following configurations to your launch.json file.

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "ng serve",
            "url": "http://localhost:4200/#",
            "webRoot": "${workspaceRoot}"
        },
        {
            "type": "chrome",
            "request": "launch",
            "name": "ng test",
            "url": "http://localhost:9876/debug.html",
            "webRoot": "${workspaceRoot}"
        }
    ]
}

Select the “ng serve” debug config, press Shift+Cmd+S to serve the app, then press F5 to hit your breakpoint.

ng-serve-debug.png

To debug unit tests, start the tests be pressing Shift+Cmd+T, select the “ng test” debug config, and press F5.  You should hit your breakpoint and be able to add watches, view the call stack, and step through your code.

ng-test-debug.png

I wrote a VS Code recipe for Angular CLI debugging, which contains further information, including installation instructions, gotchas and workarounds.

It’s a great time to be an Angular developer, and VS Code can help you be more productive — if you know how to bend it to your will.  Enjoy!

About Tony Sneed

Married with three children.
This entry was posted in Technical and tagged , . Bookmark the permalink.

One Response to Turbocharge VS Code for Angular Development

  1. Thanks for sharing these tips for VS Code. It is really helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s