If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular applications, then step right in.
如果你在为语法,规则和Angular应用结构寻找一个特定的风格指南,请继续阅读。
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.
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.
We apply the [Single Responsibility Principle](https:\/\/en.wikipedia.org/wiki/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.
**Do** define one thing (e.g. service or component) per file.
**采用** 每个文件定义一个东西(比如服务或者组件)。
.s-rule.consider
:marked
**Consider** limiting files to 400 lines of code.
**考虑** 限制文件到400行代码之内。
.s-why
:marked
**Why?** One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.
**为何?** 一个组件一个文件,让它非常容易阅读、维护,并且能防止在版本控制里与团队冲突。
.s-why
:marked
**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,
**Why?** A single component can be the default export for its file which facilitates lazy loading with the Component Router.
**为何?** 一个单独的组件能是该文件默认的输出,可以支持组件路由的懒加载。
:marked
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*.
As the app grows, this rule becomes even more important.
随着应用的长大,本规则会变得更加重要。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Small Functions
### 小函数
<a id="01-02"></a>
#### Style 01-02
### 风格01-02
.s-rule.do
:marked
**Do** define small functions
**采用** 定义小的函数
.s-rule.consider
:marked
**Consider** limiting to no more than 75 lines.
**考虑** 限制在75行之内
.s-why
:marked
**Why?** Small functions are easier to test, especially when they do one thing and serve one purpose.
**为何?** 小函数更加容易被测试,特别是当它们只做一件事,为一个目的服务的时候。
.s-why
:marked
**Why?** Small functions promote reuse.
**为何?** 小函数促进代码重用。
.s-why
:marked
**Why?** Small functions are easier to read.
**为何?** 小函数更加容易阅读。
.s-why
:marked
**Why?** Small functions are easier to maintain.
**为何?** 小函数更加容易维护。
.s-why.s-why-last
:marked
**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 conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.
命名规则是一个对维护性和可读性非常重要。本指南为文件名和标志名字推荐了命名规则。
.l-main-section
:marked
### General Naming Guidelines
### 常规命名基准线
<a id="02-01"></a>
#### Style 02-01
#### 风格02-01
.s-rule.do
:marked
**Do** use consistent names for all symbols.
**采用** 为所有标志使用一致的名字。
.s-rule.do
:marked
**Do** follow 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.
**为何?** 命名规则应该简单地帮助我们快速找到我们的代码并让它更加容易被理解。
.s-why.s-why-last
:marked
**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.
**Do** use dots to separate the descriptive name from the type.
**采用** 使用点来分离描述性名字和类型名字。
.s-rule.do
:marked
**Do** use consistent names for all components following a pattern that describes the component's feature then its type. A recommended pattern is `feature.type.ts`.
**Do** use 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 pattern matching for any automated tasks.
**为何?** 为任何自动任务提供一个模式配对。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Components and Directives
### 组件和指令
<a id="02-03"></a>
#### Style 02-03
#### 风格02-03
.s-rule.do
:marked
**Do** use consistent names for all assets named after what they represent.
**采用** 为所有东西使用统一的命名:以它们所代表的东西命名
.s-rule.do
:marked
**Do** use upper camel case for symbols. Match the name of the symbol to the naming of the file.
**采用** 使用大写驼峰命名法来命名所有符号(类)。配对符号的名字和它所在的文件名字。
.s-rule.do
:marked
**Do** append the symbol name with the suffix that it represents.
**采用** 把符号所代表的(比如组件、服务、指令等)附加到符号名字右面。
.s-why
:marked
**Why?** Provides a consistent way to quickly identify and reference assets.
**为何?** 提供一个前后一致的方法,用来迅速辨识和引用东西。
.s-why
:marked
**Why?** Upper camel case is conventional for identifying objects that can be instantiated using a constructor.
**为何?** 使用大写驼峰命名法是一个辨识可以使用构造函数来实例化的对象的常规。
.s-why.s-why-last
:marked
**Why?** The `Component` suffix is more commonly used and is more explicitly descriptive.
**为何?** `Component`后缀是更加常见的用法,它具有精准的描述性。
- var top="vertical-align:top"
table(width="100%")
col(width="50%")
col(width="50%")
tr
th Symbol Name
th File Name
tr(style=top)
td
code-example.
@Component({ ... })
export class AppComponent {}
td
:marked
app.component.ts
tr(style=top)
td
code-example.
@Component({ ... })
export class HeroesComponent
td
:marked
heroes.component.ts
tr(style=top)
td
code-example.
@Component({ ... })
export class HeroListComponent
td
:marked
hero-list.component.ts
tr(style=top)
td
code-example.
@Component({ ... })
export class HeroDetailComponent
td
:marked
hero-detail.component.ts
tr(style=top)
td
code-example.
@Directive({ ... })
export class ValidationDirective
td
:marked
validation.directive.ts
:marked
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Service Names
### 服务名字
<a id="02-04"></a>
#### Style 02-04
#### 风格02-04
.s-rule.do
:marked
**Do** use consistent names for all services named after their feature.
**采用** 为所有服务使用前后一致的命名规则,以它们的特性来命名。
.s-rule.do
:marked
**Do** use upper camel case for services.
**采用** 使用大写驼峰命名法来命名服务。
.s-rule.do
:marked
**Do** suffix services with `Service` when it is not clear what they are (e.g. when they are nouns).
**采用** 当不是很清楚它们是什么的时候(比如它们为名词时),添加`Service`后缀。
.s-why
:marked
**Why?** Provides a consistent way to quickly identify and reference services.
**为何?** 提供一个前后统一的方法来快速识别和引用服务。
.s-why
:marked
**Why?** Clear service names such as `logger` do not require a suffix.
**为何?** 清楚的服务名字比如`logger`不需要一个后缀。
.s-why.s-why-last
:marked
**Why?** Service names such as `Credit` are nouns and require a suffix and should be named with a suffix when it is not obvious if it is a service or something else.
**Do** put bootstrapping and platform logic for the app in a file named `main.ts`.
**采用** 把应用的引导程序和平台逻辑放到一个名字为`main.ts`的文件里。
.s-rule.avoid
:marked
**Avoid** putting app logic in the `main.ts`. Instead consider placing it in a Component or Service.
**避免** 把应用逻辑放到`main.ts`里。而是考虑把它放到一个组件或服务里面。
.s-why
:marked
**Why?** Follows a consistent convention for the startup logic of an app.
**为何?** 遵循一个前后统一的规则来命名应用的启动逻辑。
.s-why.s-why-last
:marked
**Why?** Follows a familiar convention from other technology platforms.
**为何?** 从其他技术平台借鉴一个熟悉的命名规则。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Directive Selectors
### 指令选择器
<a id="02-06"></a>
#### Style 02-06
#### 风格02-06
.s-rule.do
:marked
**Do** Use lower camel case for naming the selectors of our directives.
**采用** 使用小驼峰命名法来命名指令的选择器。
.s-why
:marked
**Why?** Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.
**为何?** 保持指令里定义的属性名字与他们绑定的视图的HTML属性名字一致。
.s-why.s-why-last
:marked
**Why?** The Angular 2 HTML parser is case sensitive and will recognize lower camel case.
**为何?** Angular 2 HTML剖析器是大小写敏感的,而且它识别小写驼峰写法。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Custom Prefix for Components
### 为组件自定义前缀
<a id="02-07"></a>
#### Style 02-07
#### 风格02-07
.s-rule.do
:marked
**Do** use a custom prefix for the selector of our components. For example, the prefix `toh` represents from **T**our **o**f **H**eroes and the prefix `admin` represents an admin feature area.
Have a near term view of implementation and a long term vision. Start small but keep in mind where the app is heading down the road.
准备一个短期的执行方案和一个长期的执行方案。从零开始,但是时刻考虑应用接下来要走的路。
All of the app's code goes in a folder named `app`. All content is 1 feature per file. Each component, service, and pipe is in its own file. All 3rd party vendor scripts are stored
in another folder and not in the `app` folder. We didn't write them and we don't want them cluttering our app. Use the naming conventions for files in this guide.
### LIFT (定位`L`ocate、识别`I`dentity、平坦`F`lattest、尝试`T`ry遵循不重复自己DRY - Do Not Repeat Yourself规则)
<a id="04-01"></a>
#### Style 04-01
#### 风格04-01
.s-rule.do
:marked
**Do** structure the app such that we can `L`ocate our code quickly, `I`dentify the code at a glance, keep the `F`lattest structure we can, and `T`ry to be DRY.
**采用** 组织应用的结构,达到这些目的:快速定位(`L`ocate)代码、一眼识别(`I`dentify)代码、尽量保持结构平坦(`F`lattest)和尝试`T`ry遵循不重复自己DRY - Do Not Repeat Yourself规则。
.s-rule.do
:marked
**Do** define the structure to follow these four basic guidelines, listed in order of importance.
**采用** 按照下面按照重要顺序列出的四个基本基准线来定义结构。
.s-why.s-why-last
:marked
**Why?** LIFT Provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly.
Another way to check our app structure is to ask ourselves: How quickly can we open and work in all of the related files for a feature?
**Do** make locating our code intuitive, simple and fast.
**采用** 直观、简单和快速的定位我们的代码。
.s-why.s-why-last
:marked
**Why?** We find this to be super important for a project. If we cannot find the files we need to work on quickly, we will not be able to work as efficiently as possible,
and the structure needs to change. We may not know the file name or where its related files are, so putting them in the most intuitive locations and near each other saves a ton of time.
A descriptive folder structure can help with this.
There are deviations of the 1 per file rule when we have a set of very small features that are all related to each other, as they are still easily identifiable.
**Do** keep a flat folder structure as long as possible.
**采用** 尽可能保持一个平坦的目录结构。
.s-rule.consider
:marked
**Consider** creating fodlers when we get to seven or more files.
**考虑** 当我们有7个或更多的文件时才新建目录。
.s-why.s-why-last
:marked
**Why?** Nobody wants to search seven levels of folders to find a file. In a folder structure there is no hard and fast number rule, but when a folder has seven to ten files,
that may be time to create subfolders. We base it on our comfort level. Use a flatter structure until there is an obvious value (to help the rest of LIFT) in creating a new folder.
**Avoid** being so DRY that we sacrifice readability.
**避免** 过度DRY,以致牺牲了阅读性。
.s-why.s-why-last
:marked
**Why?** Being DRY is important, but not crucial if it sacrifices the others in LIFT, which is why we call it T-DRY. We don’t want to type `hero-view.component.html` for a view because,
well, it’s obviously a view. If it is not obvious or by convention, then we name it.
.example-title Overall Folder and File Structure 整体目录和文件结构
.filetree
.file src
.children
.file app
.children
.file +heroes
.children
.file hero
.children
.file hero.component.ts|html|css|spec.ts
.file index.ts
.file hero-list
.children
.file hero-list.component.ts|html|css|spec.ts
.file index.ts
.file shared
.children
.file hero.model.ts
.file hero.service.ts|spec.ts
.file index.ts
.file heroes.component.ts|html|css|spec.ts
.file index.ts
.file shared
.children
.file ...
.file app.component.ts|html|css|spec.ts
.file main.ts
.file index.html
.file ...
:marked
.l-sub-section
:marked
While we prefer our Components to be in their own dedicated folder, another option for small apps is to keep Components flat (not in a dedicated folder).
This adds up to four files to the existing folder, but also reduces the folder nesting. Be consistent.、
**Why?** Separates shared files from the components within a feature.
**为何?** 在一个特征范围内,分离出组件共享的文件。
.s-why.s-why-last
:marked
**Why?** Makes it easier to locate shared files within a component feature.
**为何?** 使得在一个特征的组件群内,更加容易定位共享文件。
.example-title Shared Folder 共享的目录
.filetree
.file src
.children
.file app
.children
.file +heroes
.children
.file hero
.children
.file ...
.file hero-list
.children
.file ...
.file shared
.children
.file hero-button
.children
.file ...
.file hero.model.ts
.file hero.service.ts|spec.ts
.file index.ts
.file heroes.component.ts|html|css|spec.ts
.file index.ts
.file shared
.children
.file exception.service.ts|spec.ts
.file index.ts
.file nav
.children
.file ...
.file app.component.ts|html|css|spec.ts
.file main.ts
.file index.html
.file ...
:marked
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Folders-by-Feature Structure
### 单特征目录结构
<a id="04-08"></a>
#### Style 04-08
#### 风格04-08
.s-rule.do
:marked
**Do** create folders named for the feature they represent.
**采用** 把目录的名字命名为它包含的特征名字。
.s-why
:marked
**Why?** A developer can locate the code, identify what each file represents at a glance, the structure is as flat as it can be, and there is no repetitive nor redundant names.
**Do** define Components as elements via the selector.
**采用** 通过选择器来定义个充当元素的组件。
.s-why
:marked
**Why?** Components have templates containing HTML and optional Angular template syntax. They are most associated with putting content on a page, and thus are more closely aligned with elements.
**Do** use [`@Input`](https://angular.io/docs/ts/latest/api/core/Input-var.html) and [`@Output`](https://angular.io/docs/ts/latest/api/core/Output-var.html) instead of
the `inputs` and `outputs` properties of the [`@Directive`](https://angular.io/docs/ts/latest/api/core/Directive-decorator.html) and [`@Component`](https://angular.io/docs/ts/latest/api/core/Component-decorator.html) decorators:
**Do** place the `@Input()` or `@Output()` on the same line as the property they decorate.
**采用** 把`@Input()`或者`@Output()`放到他们装饰的属性的同一行。
.s-why
:marked
**Why?** It is easier and more readable to identify which properties in a class are inputs or outputs.
**为何?** 这样可以更容易在一个类里面识别哪个属性是inputs或outputs。
.s-why
:marked
**Why?** If we ever need to rename the property or event name associated to [`@Input`](https://angular.io/docs/ts/latest/api/core/Input-var.html) or [`@Output`](https://angular.io/docs/ts/latest/api/core/Output-var.html) we can modify it on a single place.
**为何?** 如果我们需要重命名[`@Input`](https://angular.io/docs/ts/latest/api/core/Input-var.html) or [`@Output`](https://angular.io/docs/ts/latest/api/core/Output-var.html)相关的属性或者事件,我们可以在一个地方修改。
.s-why
:marked
**Why?** The metadata declaration attached to the directive is shorter and thus more readable.
**为何?** 依附到指令的元数据声明比较短,易于阅读。
.s-why.s-why-last
:marked
**Why?** Placing the decorator on the same line makes for shorter code and still easily identifies the property as an input or output.
**Avoid** renaming inputs and outputs, when possible.
**避免** 如果可能,重命名inputs和outputs。
.s-why.s-why-last
:marked
**Why?** May lead to confusion when the output or the input properties of a given directive are named a given way but exported differently as a public API.
**Do** place properties up top followed by methods.
**采用** 把属性放到顶部,方法紧跟。
.s-rule.do
:marked
**Do** place private members after public members, alphabetized.
**采用** 按照字母顺序排列,先放公共成员,再放私有成员。
.s-why.s-why-last
:marked
**Why?** Placing members in a consistent sequence makes it easy to read and helps we instantly identify which members of the component serve which purpose.
**Why?** The property or method name associated with @HostBinding or respectively @HostListener should be modified only in a single place - in the directive's class.
In contrast if we use host we need to modify both the property declaration inside the controller, and the metadata associated to the directive.
**Do** provide services to the Angular 2 injector at the top-most component where they will be shared.
**采用** 在服务被共享范围内的顶级组件里提供服务到Angular 2的注入器里。
.s-why
:marked
**Why?** The Angular 2 injector is hierarchical.
**为何?** Angular 2注入器是层次性的。
.s-why
:marked
**Why?** When providing the service to a top level component, that instance is shared and available to all child components of that top level component.
**为何?** 当在一个顶层组件提供一个服务是,该实例在被所有该顶级组件的子级组件能见并共享。
.s-why
:marked
**Why?** This is ideal when a service is sharing methods or state.
**为何?** 一个服务共享方法或状态时,这是一个理想的方法。
.s-why.s-why-last
:marked
**Why?** This is not ideal when two different components need different instances of a service.
In this scenario it would be better to provide the service at the component level that needs the new and separate instance.
**Do** use the `@Injectable` class decorator instead of the `@Inject` parameter decorator when using types as tokens for the dependencies of a service.
**Why?** When a service accepts only dependencies associated with type tokens, the `@Injectable()` syntax is much less verbose compared to using `@Inject()` on each individual constructor parameter.
**Do** refactor logic for making data operations and interacting with data to a service.
**采用** 把数据操作和数据互动重构到一个服务里。
.s-rule.do
:marked
**Do** make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.
**采用** 让数据服务负责XHR调用、本地储存、内存储存或者其他数据操作。
.s-why
:marked
**Why?** The component's responsibility is for the presentation and gathering of information for the view.
It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service,
and lets the component be simpler and more focused on the view.
**Why?** This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.
**为何?** 在测试一个使用数据服务的组件时,可以让数据调用更易被测试(模仿或者真实)。
.s-why.s-why-last
:marked
**Why?** Data service implementation may have very specific code to handle the data repository. This may include headers, how to talk to the data, or other services such as `Http`.
Separating the logic into a data service encapsulates this logic in a single place hiding the implementation from the outside consumers (perhaps a component),
also making it easier to change the implementation.
Client-side routing is important for creating a navigation flow between a component tree hierarchy, and composing components that are made of many other child components.
在组件树阶层间创建一个导航流和在组合多个子级组件组成的组件时,客户端路由是很重要的。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### Component Router
### 组件路由器
<a id="10-01"></a>
#### Style 10-01
#### 风格10-01
.s-rule.do
:marked
**Do** separate route configuration into a routing component file, also known as a component router.
**采用** 分离路由设置到一个路由组件文件,也叫作组件路由器。
.s-rule.do
:marked
**Do** use a `<router-outlet>` in the component router, where the routes will have their component targets display their templates.
**Consider** adjusting the rules in codelyzer to suit your needs.
**考虑** 调整codelyzer的规则来满足你的需求。
a(href="#toc") Back to top
a(href="#toc") 回到顶部
.l-main-section
:marked
### File Templates and Snippets
### 文件模板和片段
<a id="A-02"></a>
#### Style A-02
#### 风格A-02
.s-rule.do
:marked
**Do** use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs.
**Consider** using [snippets](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) for [Visual Studio Code](https://code.visualstudio.com/) that follow these styles and guidelines.
**考虑** 使用[Visual Studio Code](https://code.visualstudio.com/)的[snippets](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2)来跟随这些风格和基准线。