Optimizing VS Code for Angular
It is essential to optimize your IDE to have a great development experience. If you leverage the automated tools that I present in this section, you can quickly configure your IDE and your Angular project with dozens of settings that work well together.
Configuring your project automatically
To quickly apply configuration steps covered in the upcoming chapters, run the commands that follow:
- Install the Angular VS Code task:
npm i -g mrm-task-angular-vscode
- Apply the Angular VS Code configuration:
npx mrm angular-vscode
- Install the npm Scripts for the Docker task:
npm i -g mrm-task-npm-docker
- Apply the npm Scripts for Docker configuration:
npx mrm npm-docker
These settings are continually tweaked to adapt to the ever-evolving landscape of extensions, plugins, Angular, and VS Code. Always make sure to install a fresh version of the task by rerunning the install command to get the latest version.
- Execute
npm run style:fix
- Execute
npm run lint:fix
For more information on the mrm tasks, refer to:
- https://github.com/expertly-simple/mrm-task-angular-vscode
- https://github.com/expertly-simple/mrm-task-npm-docker
- https://github.com/expertly-simple/mrm-task-npm-aws
Note that mrm-task-npm-aws
sets up npm scripts for AWS ECS, which is used in Chapter 13, Highly Available Cloud Infrastructure on AWS.
You may verify your configuration against the sample projects on GitHub. However, note that the configuration pieces will be applied at the root of the repository and not under the projects
folder.
The next three sections cover the settings that were automatically applied previously. Feel free to skip ahead and refer back if you have questions.
VS Code auto save
Saving files all the time can get tedious. You can enable automatic saving by doing the following:
- Open VS Code
- Toggle the setting under File | Auto Save
You can further customize many aspects of VS Code's behavior by launching Preferences. The keyboard shortcut to launch Preferences is [Ctrl + ,] on Windows and [ + ,] on macOS.
IDE settings
You can share such settings with your coworkers by creating a .vscode
folder in the root of your project directory and placing a settings.json
file in it. If you commit this file to the repository, everyone will share the same IDE experience. Unfortunately, individuals aren't able to override these settings with their local preferences, so ensure that shared settings are minimal and are agreed upon as a team norm.
Here are the customizations that I use for an optimal, battery-life-conscious Angular development experience:
.vscode/settings.json
{
"debug.openExplorerOnEnd": true,
"editor.tabSize": 2,
"editor.rulers": [90],
"editor.autoIndent": "full",
"editor.cursorBlinking": "solid",
"editor.formatOnType": false, // Adjust the intensity of
"editor.formatOnPaste": false, auto-formatting to taste
"editor.formatOnSave": true,
"editor.minimap.enabled": false,
"editor.codeActionsOnSave": {
"source.organizeImports": false,
"source.fixAll.tslint": true,
},
"explorer.openEditors.visible": 0,
"files.trimTrailingWhitespace": true,
"files.autoSave": "onFocusChange",
"git.confirmSync": false,
"git.enableSmartCommit": true,
"npm.enableScriptExplorer": true,
"typescript.tsdk": "node_modules/typescript/lib",
"workbench.iconTheme": "material-icon-theme", // Requires
Material Icon
Theme Extension
"auto-close-tag.SublimeText3Mode": true, // Requires Auto
Close Tag Extension
"html.autoClosingTags": false,
"peacock.affectActivityBar": true, // Requires Peacock
"peacock.affectStatusBar": true, Extension
"peacock.affectTitleBar": false,
"workbench.colorCustomizations": {
"activityBar.background": "#d04649",
"activityBar.activeBorder": "#37cb34",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#37cb34",
"activityBarBadge.foreground": "#15202b",
"statusBar.background": "#b52e31",
"statusBarItem.hoverBackground": "#d04649",
"statusBar.foreground": "#e7e7e7"
},
"peacock.color": "#b52e31",
"gitlens.menus": { // Requires GitLens
"editorGroup": false Extension
},
"ng-evergreen.upgradeChannel": "Latest" // Requires Angular
Evergreen Extension
}
In later sections, as we add tools that enforce our coding style, be careful not to introduce new settings that overlap or contradict each other.
IDE extensions
For a magical development experience with VS Code and Angular, you should install the Angular Essentials extension pack created and curated by John Papa. John Papa is one of the leading champions and thought leaders in the Angular community. He continuously and relentlessly seeks the best possible development experience you can attain so that you are more productive and happier as a developer. To learn more about Angular Essentials, see this blog post at https://johnpapa.net/rec-ng-extensions and the GitHub repo at https://github.com/johnpapa/vscode-angular-essentials.
I highly recommend you follow John Papa on Twitter at @john_papa
.
Similar to settings, you can also share recommended extensions via a JSON file. These are the extensions that I use for Angular development:
.vscode/extensions.json
{
"recommendations":[
"johnpapa.angular-essentials",
"PKief.material-icon-theme",
"formulahendry.auto-close-tag",
"ms-azuretools.vscode-docker",
"eamodio.gitlens",
"WallabyJs.quokka-vscode",
"amatiasq.sort-imports",
"DSKWRK.vscode-generate-getter-setter",
"esbenp.prettier-vscode",
"HookyQR.beautify",
"expertly-simple.ng-evergreen",
"msjsdiag.debugger-for-edge"
]
}
VS Code also recommends some extensions for you to install. I would caution against installing too many extensions, as these noticeably start slowing down the launch performance and optimal operation of VS Code.
The VS Code ecosystem is an ever-evolving, dynamic, and rich ecosystem. As such, certain extensions or settings may disappear, stop working, or have bugs in them. If you run into any trouble or are simply curious, you can find the latest versions of my preferred VS Code configuration files on GitHub at http://bit.ly/ngCodeSettings.
Scripting code styling and linting
You can customize the code styling enforcement and code generation behavior in VS Code and the Angular CLI. The most crucial goal of automating the enforcement of code styling and linting rules is to set common ground between developers. If the team can't agree on what styling to follow, a coin toss is better than no agreement. Development teams should be focused on code quality and let automated tools worry about the indentation of their code, location of brackets, and spaces between parentheses. In large teams, any deviation in styling can cause significant headaches with merge conflicts. It is highly recommended that you implement mechanisms to enforce standards.
I prefer StandardJS settings for JavaScript, which codify a minimal approach to writing code while maintaining high readability. This means two spaces for tabs and no semicolons. In addition to the reduced keystrokes, StandardJS also takes less horizontal space, which is especially valuable when your IDE can only utilize half of the screen, with the other half taken up by the browser. You can read more about StandardJS at: https://standardjs.com/.
With the default settings, your code looks like:
import { AppComponent } from "./app.component";
With StandardJS settings, your code looks like:
import { AppComponent } from './app.component'
If you don't like this style, it is okay. While I'll be sharing my preferred settings following, feel free to tweak them to your liking. The mechanism we implement to enforce the rules remains the same regardless.
To apply and enforce code styling rules, we use some tools that provide both a CLI tool and a VS Code extension:
- Prettier – used to format
.ts
files - ImportSort/SortImports – used to organize TypeScript import statements
- Beautify – used to format
.html
files, - TSLint – used as a static code analysis tool to check code readability, maintainability, and functionality errors
Our goal is to end up with four scripts:
style
– to check if our code adheres to styling rulesstyle:fix
– to automatically format code files as per styling ruleslint
– to check if our code has any linting errorslint:fix
– to automatically fix auto-fixable linting errors
The style and lint commands would be utilized by our CI server to ensure that every team member is adhering to the same coding standards. The style:fix
and lint:fix
commands would help developers adhere to coding standards with as little effort as possible.
These tools are constantly updated. The behavior of these tools may shift over time, so keep an eye out and don't hesitate to experiment with adding/removing tools to this mixture to achieve the configuration that works for you.
Before we set up our dependencies and configuration files, ensure that all the extensions recommended in the IDE extensions section are installed.
Configuring tooling
You can start making the configuration changes by following these steps:
- Make sure the Prettier – Code formatter, TSLint, sort-imports, and Beautify extensions are installed (already included in
extensions.json
from the previous section) - Install the CLI tools by executing the following command:
npm i -D prettier tslint-config-prettier tslint-plugin-prettier npm i -D js-beautify npm i -D import-sort import-sort-cli import-sort-parser-typescript import-sort-style-module npm i -D tslint tslint-etc
With npm, you can use
i
as an alias forinstall
and-D
instead of the more verbose--save- dev
option. However, if you mistype-D
as-d
, you end up saving the package as a production dependency. - Edit
package.json
by appending animportSort
attribute at the end of the file:package.json ... "importSort": { ".ts, .tsx": { "parser": "typescript", "style": "module", "options": {} } } ...
- Update the
tslint.json
rules for integration with Prettier andtslint-etc
:tslint.json { "extends": [ "tslint:recommended", "tslint-config-prettier", "tslint-plugin-prettier", "tslint-etc" ], "rules": { "prettier": true, "no-unused-declaration": true, ... "quotemark": [true, "single", "avoid-escape"], ... "semicolon": [ true, "never"], ... "max-line-length": [ true,90], ... }
- Add a new file to the root of your project, named
.jsbeautifyrc
:.jsbeautifyrc { "indent_size": 2, "wrap_line_length": 90, "language": { "html": [ "html" ] } }
- Add a new file to the root of your project, named
.prettierrc
:. prettierrc { "tabWidth": 2, "useTabs": false, "printWidth": 90, "semi": false, "singleQuote": true, "trailingComma": "es5", "jsxBracketSameLine": true }
- Add a new file to the root of your project, named
.prettierignore
. Note that this file doesn't have curly brackets:. prettierignore **/*.html
Now we are done configuring all the tooling necessary to implement our style and lint scripts.
Implementing a style checker and fixer
Let's implement npm scripts for style and style:fix
commands. Npm scripts are a great way to document CLI scripts that your team needs to execute across different platforms and even on a CI server.
Now, let's add our first script:
- Edit the
package.json
scripts attribute to addstyle
andstyle:fix
commands:package.json ... "scripts": { "style:fix": "import-sort --write \"**/{src,tests,e2e}/*.ts\" && prettier --write \"**/{src,tests,e2e}/*.{*css,ts}\" && js-beautify \"src/**/*.html\"", "style": "import-sort -l \"**/{src,tests,e2e}/*.ts\" && prettier --check \"**/{src,tests,e2e}/*.{*css,ts}\"", ... } ...
- Execute
npm run style
to see the files that do not adhere to styling rules - Execute
npm run style:fix
to update all your files to the new style - Observe all the file changes in GitHub Desktop
- Commit your changes
When you utilize inline templates in Angular, the inlined portion of HTML is formatted by Prettier instead of Beautify. In most of these cases, your code will look good, but if your HTML elements have too many attributes, your code will be formatted in a very verbose manner. In order to prevent this from happening, you may select the relevant HTML code and run the Beautify selection command within VS Code. If you add // prettier-ignore
above the template property, Prettier will stop messing up your beautified HTML.
Now, let's configure our linting scripts.
Implementing a lint checker and fixer
A lint
command already exists in package.json
. We overwrite the existing lint
command with our own and implement an additional lint:fix
command.
Add the new scripts:
- Edit the
package.json
scripts attribute to replacelint
and addlint:fix
commands:package.json ... "scripts": { ... "lint": "tslint --config tslint.json --project . -e \"**/{test,polyfills}.ts\"", "lint:fix": "tslint --config tslint.json --fix --project . -e \"**/{test,polyfills}.ts\"", ... } ...
Note that unlike the style scripts, we're excluding
test.ts
andpolyfills.ts
from being linted. These files ship with linting errors; they are unlikely to be edited frequently and since they have no bearing on the quality of our code, we can safely ignore them. - Execute
npm run lint
to see the files that have linting errors - Execute
npm run lint:fix
to fix any auto-fixable errors - If there are further errors, then Ctrl/cmd + click on the files and manually fix the errors
- Observe all the file changes in GitHub Desktop
- Commit your changes
- Don't forget to push your changes to your repository!
Sometimes, as you type in new code or generate new components using the Angular CLI, you may encounter double-quotes or semicolons being underlined with a red squiggly line to indicate an issue. We have configured VS Code to automatically format files on saving, which happens automatically when the window loses focus. When auto-formatting is triggered, the file updates and formatting related errors disappear.
When we cover CI in Chapter 4, Automated Testing, CI, and Release to Production, we are going to run our style and lint checker as part of our pipeline.
Next, configure the ng tool to get the autocomplete functionality in the terminal.
Configuring Angular CLI autocomplete
You can get an autocomplete experience in your terminal when using the Angular CLI. Execute the appropriate command for your *nix
environment:
- For the bash shell:
$ ng completion --bash >> ~/.bashrc $ source ~/.bashrc
- For the zsh shell:
$ ng completion --zsh >> ~/.zshrc $ source ~/.zshrc
- For Windows users using the Git bash shell:
$ ng completion --bash >> ~/.bash_profile $ source ~/.bash_profile
Next, let's learn about the VS Code Auto Fixer.
VS Code Auto Fixer
Sometimes, a yellow bulb icon appears next to a line of code. This might happen because you have typed some code that violates a rule defined in tslint.json
. If you click on the bulb, you will see an action labeled as a Fix. You can take advantage of these auto-fixers to allow VS Code to fix your code automatically. The screenshot that follows shows an example of an Unnecessary semicolon issue:
Figure 2.7: VS Code Auto Fixer
Congratulations – you're done setting up your development environment!