Angular目录结构
Angular目录结构
Angular 项目推荐目录结构整理
📁 顶层目录结构(src/app 下)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
src/
├── app/
│ ├── components/ # 可复用的 UI 组件(小块展示组件)
│ ├── pages/ # 页面组件(路由页面,每个对应一个功能页)
│ ├── services/ # 全局服务(API 调用、状态管理等)
│ ├── models/ # 全局数据模型(interface 类型定义)
│ ├── pipes/ # 公共管道(格式转换,如日期、大小写等)
│ ├── directives/ # 自定义指令(交互行为增强)
│ ├── guards/ # 路由守卫(如登录检查)
│ ├── app.component.ts # 根组件
│ ├── app.routes.ts # 路由配置
│ └── app.config.ts # Angular 17 的 provide 配置入口
├── assets/ # 静态资源(图片、图标等)
├── environments/ # 不同构建环境的变量配置
├── main.ts # 应用入口
├── index.html # HTML 页面入口
├── styles.css # 全局样式文件
📁 组件目录结构(components/)
1
2
3
4
5
6
7
8
components/
├── beer-card/
│ ├── beer-card.component.ts
│ ├── beer-card.component.html
│ └── beer-card.component.css
├── rating-stars/
│ ├── rating-stars.component.ts
│ └── rating-stars.component.html
说明:用于封装复用的小组件,不直接挂在路由上,由页面或其他组件引用。
📁 页面目录结构(pages/)
1
2
3
4
5
6
7
8
9
pages/
├── home/
│ ├── home.component.ts
│ ├── home.component.html
│ ├── home.component.css
│ └── home.service.ts # 页面专属服务(可选)
├── details/
│ ├── details.component.ts
│ └── details.component.html
说明:每个页面是一个功能模块,一般配合路由使用。
📁 服务目录结构(services/)
1
2
3
services/
├── beer.service.ts # 可复用的全局服务
├── auth.service.ts # 登录权限处理
说明:业务核心逻辑和数据来源,提供给多个页面或组件调用。
📁 模型目录结构(models/)
1
2
3
models/
├── beer-entry.ts # interface 定义
├── user.ts
说明:用于集中管理 TypeScript 类型,提高可维护性和类型检查。
📁 公共工具目录结构(pipes/ 和 directives/)
1
2
3
4
5
6
7
pipes/
├── truncate.pipe.ts
├── format-date.pipe.ts
directives/
├── autofocus.directive.ts
├── scroll-to-top.directive.ts
说明:公共功能,适用于多个页面/组件,提高可复用性。
📁 环境变量目录结构(environments/)
1
2
3
environments/
├── environment.ts # 默认开发环境
├── environment.prod.ts # 生产环境
说明:在构建时会自动根据 --configuration
切换环境变量文件。
✅ 总结
- 页面组件放在
pages/
- 可复用 UI 放在
components/
- 服务可全局(services/)或页面内(pages/…)
- 类型定义放在
models/
- 公共工具函数放
pipes/
、directives/
- 构建环境变量放在
environments/
本文由作者按照 CC BY 4.0 进行授权