神刀安全网

Angular 2 Style Guide

Welcome to the Angular 2 Style Guide

Purpose

If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular applications, then step right in.

The purpose of this style guide is to provide guidance on building Angular applications by showing the conventions we use and, more importantly, why we choose them.

Style Vocabulary

Each guideline describes either a good or bad practice, and all have a consistent presentation.

The wording of each guideline indicates how strong the recommendation is.

Dois one that should always be followed. Always might be a bit too strong of a word. Guidelines that literally should always be followed are extremely rare. On the other hand, we need a really unusual case for breaking a Do guideline.

Considerguidelines should generally be followed. If you fully understand the meaning behind the guideline and have a good reason to deviate, then do so. Please strive to be consistent.

Avoidindicates something we should almost never do. Code examples to avoid have an unmistakeable red header.

File Structure Conventions

Some code examples display a file that has one or more similarly named companion files. (e.g. hero.component.ts and hero.component.html).

The guideline will use the shortcut hero.component.ts|html|css|spec to represent those various files. Using this shortcut makes this guide’s file structures easier to read and more terse.

Table of Contents

Single Responsibility

We apply the Single Responsibility Principle to all Components, Services, and other symbols we create. This helps make our app cleaner, easier to read and maintain, and more testable.

Rule of One

Style 01-01

Dodefine one thing (e.g. service or component) per file.

Considerlimiting files to 400 lines of code.

Why?One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.

Why?One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

Why?A single component can be the default export for its file which facilitates lazy loading with the Component Router.

The key is to make the code more reusable, easier to read, and less mistake prone.

The following negative example defines the AppComponent , bootstraps the app, defines the Hero model object, and loads heroes from the server … all in the same file. Don’t do this .

AVOID: app/heroes/hero.component.ts

/* avoid */ import { bootstrap } from ‘@angular/platform-browser-dynamic’; import { Component, OnInit } from ‘@angular/core’; class Hero { id: number; name: string; } @Component({ selector: ‘my-app’, template: ` <h1>{{title}}</h1> <pre>{{heroes | json}}</pre> `, styleUrls: [‘app/app.component.css’] }) class AppComponent implements OnInit { title = ‘Tour of Heroes’; heroes: Hero[] = []; ngOnInit() { getHeroes().then(heroes => this.heroes = heroes); } } bootstrap(AppComponent, []); const HEROES: Hero[] = [ {id: 1, name: ‘Bombasto’}, {id: 2, name: ‘Tornado’}, {id: 3, name: ‘Magneta’}, ]; function getHeroes(): Promise<Hero[]> { return Promise.resolve(HEROES); // TODO: get hero data from the server; }

Better to redistribute the component and supporting activities into their own dedicated files.

import { bootstrap } from ‘@angular/platform-browser-dynamic’; import { AppComponent } from ‘./app.component’; bootstrap(AppComponent, []); // app.component.ts import { Component } from ‘@angular/core’; import { HeroesComponent } from ‘./heroes/heroes.component’; import { HeroService } from ‘./heroes/shared/hero.service’; @Component({ selector: ‘toh-app’, template: ` <toh-heroes></toh-heroes> `, styleUrls: [‘app/app.component.css’], directives: [HeroesComponent], providers: [HeroService] }) export class AppComponent { } import { Component, OnInit } from ‘@angular/core’; import { Hero } from ‘./shared/hero.model’; import { HeroService } from ‘./shared/hero.service’; @Component({ selector: ‘toh-heroes’, template: ` <pre>{{heroes | json}}</pre> ` }) export class HeroesComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.heroService.getHeroes() .then(heroes => this.heroes = heroes); } } import { Injectable } from ‘@angular/core’; import { HEROES } from ‘./mock-heroes’; @Injectable() export class HeroService { getHeroes() { return Promise.resolve(HEROES); } } export class Hero { id: number; name: string; } import { Hero } from ‘./hero.model’; export const HEROES: Hero[] = [ {id: 1, name: ‘Bombasto’}, {id: 2, name: ‘Tornado’}, {id: 3, name: ‘Magneta’}, ];

As the app grows, this rule becomes even more important.

Small Functions

Style 01-02

Dodefine small functions

Considerlimiting to no more than 75 lines.

Why?Small functions are easier to test, especially when they do one thing and serve one purpose.

Why?Small functions promote reuse.

Why?Small functions are easier to read.

Why?Small functions are easier to maintain.

Why?Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.

Naming

Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.

General Naming Guidelines

Style 02-01

Douse consistent names for all symbols.

Dofollow a pattern that describes the symbol’s feature then its type. The recommended pattern is feature.type.ts .

Why?Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency.

Why?The naming conventions should simply help us find our code faster and make it easier to understand.

Why?Names of folders and files should clearly convey their intent. For example, app/heroes/hero-list.component.ts may contain a component that manages a list of heroes.

Separate File Names with Dots and Dashes

Style 02-02

Douse dashes to separate words.

Douse dots to separate the descriptive name from the type.

Douse consistent names for all components following a pattern that describes the component’s feature then its type. A recommended pattern is feature.type.ts .

Douse conventional suffixes for the types including *.service.ts , *.component.ts , *.pipe.ts . Invent other suffixes where desired, but take care in having too many.

Why?Provides a consistent way to quickly identify what is in the file.

Why?Provides a consistent way to quickly find a specific file using an editor or IDE’s fuzzy search techniques.

Why?Provides pattern matching for any automated tasks.

Components and Directives

Style 02-03

Douse consistent names for all assets named after what they represent.

Douse upper camel case for symbols. Match the name of the symbol to the naming of the file.

Doappend the symbol name with the suffix that it represents.

Why?Provides a consistent way to quickly identify and reference assets.

Why?Upper camel case is conventional for identifying objects that can be instantiated using a constructor.

Why?The Component suffix is more commonly used and is more explicitly descriptive.

Symbol Name File Name
@Component({ … }) export class AppComponent {}

app.component.ts

@Component({ … }) export class HeroesComponent

heroes.component.ts

@Component({ … }) export class HeroListComponent

hero-list.component.ts

@Component({ … }) export class HeroDetailComponent

hero-detail.component.ts

@Directive({ … }) export class ValidationDirective

validation.directive.ts

Service Names

Style 02-04

Douse consistent names for all services named after their feature.

Douse upper camel case for services.

Dosuffix services with Service when it is not clear what they are (e.g. when they are nouns).

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Angular 2 Style Guide

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址