简体   繁体   中英

Filetype Naming Convention for Angular Classes

Angular's Style Guide lists naming conventions for common file types, such as heroes.component.ts , or heroes.service.ts , etc. But what about classes that have no decorator symbols? For example, the Heroes tutorial creates a Hero class:

export class Hero {
  id: number;
  name: string;
}

It then names this file hero.ts . A naming convention like this seems prone to chaos in the app directory. It seems logical to create a folder named classes (in the app directory), and then add a class.ts suffix to each file, such as hero.class.ts .

However, I have not seen anyone using this convention. I've seen people use a model.ts suffix, but it's unclear whether or not this is a best practice, and it is not mentioned in the Angular Style Guide .

Can anyone shed some light on this topic? Sorry if I've missed anything. Thank you advance.

Angular Style Guide explicitly says to use .model for simple models. However, you should consider 2 things:

  • there is no convention for enums . Personally I keep them inside of service or model file, depending on how it supposed to be used
  • guide allows to create other entities , so in scope of your project - you can add other "types" (recource, config)
  • if class/model/interface (eg User ) is used across application, guide suggests to keep it in shared module, which is logically right: SharedModule is supposed to be imported multiple times, while CoreModule - only once (in AppModule )

There are two ways of creating packages (folders) in your application:

  • package by layer
  • package by feature

Angular prefers "package by feature" and that's why hero class remains within hero component which it belongs to. Good post about why "package by feature" is preferred way is here .

As for classes/services which are used for several components - Angular StyleGuide suggests to use core package. If it's a component which is shared - then a shared package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM