Angular项目结构 #

一、项目目录概览 #

text
my-app/
├── .vscode/                 # VS Code配置
├── node_modules/            # 依赖包
├── src/                     # 源代码
│   ├── app/                 # 应用代码
│   ├── assets/              # 静态资源
│   ├── environments/        # 环境配置
│   ├── favicon.ico          # 网站图标
│   ├── index.html           # 入口HTML
│   ├── main.ts              # 应用入口
│   ├── styles.css           # 全局样式
│   └── polyfills.ts         # 浏览器兼容
├── angular.json             # Angular配置
├── package.json             # 项目依赖
├── tsconfig.json            # TypeScript配置
├── tsconfig.app.json        # 应用TS配置
├── tsconfig.spec.json       # 测试TS配置
└── README.md                # 项目说明

二、src目录详解 #

2.1 app目录 #

text
src/app/
├── components/              # 组件目录
│   ├── header/
│   │   ├── header.component.ts
│   │   ├── header.component.html
│   │   └── header.component.css
│   └── footer/
├── services/                # 服务目录
│   ├── user.service.ts
│   └── api.service.ts
├── models/                  # 数据模型
│   └── user.model.ts
├── pipes/                   # 管道目录
│   └── truncate.pipe.ts
├── directives/              # 指令目录
│   └── highlight.directive.ts
├── guards/                  # 路由守卫
│   └── auth.guard.ts
├── app.component.ts         # 根组件
├── app.component.html
├── app.component.css
├── app.config.ts            # 应用配置(独立组件)
└── app.routes.ts            # 路由配置

2.2 main.ts入口文件 #

typescript
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));

2.3 index.html #

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

2.4 environments环境配置 #

typescript
// environment.ts - 开发环境
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/api'
};

// environment.prod.ts - 生产环境
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com'
};

使用环境变量:

typescript
import { environment } from '../environments/environment';

if (environment.production) {
  console.log('生产环境');
}

三、核心配置文件 #

3.1 angular.json #

json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-app": {
      "projectType": "application",
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:application",
          "options": {
            "outputPath": "dist/my-app",
            "index": "src/index.html",
            "browser": "src/main.ts",
            "polyfills": ["zone.js"],
            "tsConfig": "tsconfig.app.json",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.css"],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                }
              ],
              "outputHashing": "all"
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "buildTarget": "my-app:build:production"
            }
          }
        }
      }
    }
  }
}

3.2 angular.json重要配置项 #

配置项 说明
prefix 组件选择器前缀,默认app
sourceRoot 源代码目录
outputPath 构建输出目录
assets 静态资源目录
styles 全局样式文件
scripts 全局脚本文件
budgets 构建大小限制

3.3 package.json #

json
{
  "name": "my-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "dependencies": {
    "@angular/animations": "^17.0.0",
    "@angular/common": "^17.0.0",
    "@angular/compiler": "^17.0.0",
    "@angular/core": "^17.0.0",
    "@angular/forms": "^17.0.0",
    "@angular/platform-browser": "^17.0.0",
    "@angular/platform-browser-dynamic": "^17.0.0",
    "@angular/router": "^17.0.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^17.0.0",
    "@angular/cli": "^17.0.0",
    "@angular/compiler-cli": "^17.0.0",
    "typescript": "~5.2.2"
  }
}

3.4 tsconfig.json #

json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "declaration": false,
    "experimentalDecorators": true,
    "moduleResolution": "bundler",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "lib": ["ES2022", "dom"]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

3.5 TypeScript配置项说明 #

配置项 说明
strict 启用所有严格类型检查选项
experimentalDecorators 启用装饰器
moduleResolution 模块解析策略
target 编译目标版本
lib 编译时包含的库

四、模块系统 #

4.1 NgModule(传统模块) #

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { UserService } from './services/user.service';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

4.2 NgModule配置项 #

配置项 说明
declarations 声明本模块的组件、指令、管道
imports 导入其他模块
providers 注册服务
bootstrap 指定根组件
exports 导出供其他模块使用

4.3 独立组件(Standalone Components) #

Angular 17+推荐使用独立组件:

typescript
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <input [(ngModel)]="name" />
    <p>Hello, {{ name }}!</p>
  `
})
export class UserComponent {
  name = '';
}

4.4 应用配置(app.config.ts) #

typescript
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient()
  ]
};

五、常用Angular模块 #

5.1 核心模块 #

模块 说明 常用功能
CommonModule 通用模块 *ngIf, *ngFor, DatePipe等
FormsModule 表单模块 ngModel, 表单验证
ReactiveFormsModule 响应式表单 FormGroup, FormControl
HttpClientModule HTTP模块 HttpClient服务
RouterModule 路由模块 路由配置与导航

5.2 模块导入示例 #

typescript
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';

// 独立组件中导入
@Component({
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})

// 应用配置中提供
export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideRouter(routes)
  ]
};

六、项目结构最佳实践 #

6.1 按功能模块组织 #

text
src/app/
├── core/                    # 核心模块
│   ├── services/
│   ├── guards/
│   ├── interceptors/
│   └── models/
├── shared/                  # 共享模块
│   ├── components/
│   ├── directives/
│   └── pipes/
├── features/                # 功能模块
│   ├── user/
│   ├── product/
│   └── order/
└── app.component.ts

6.2 按类型组织 #

text
src/app/
├── components/              # 所有组件
├── services/                # 所有服务
├── models/                  # 所有模型
├── pipes/                   # 所有管道
├── directives/              # 所有指令
├── guards/                  # 所有守卫
└── app.component.ts

6.3 文件命名规范 #

类型 文件名 示例
组件 *.component.ts user-list.component.ts
服务 *.service.ts user.service.ts
模型 *.model.ts user.model.ts
管道 *.pipe.ts truncate.pipe.ts
指令 *.directive.ts highlight.directive.ts
守卫 *.guard.ts auth.guard.ts

七、构建与部署 #

7.1 构建命令 #

bash
# 开发构建
ng build

# 生产构建
ng build --configuration production

# 指定输出目录
ng build --output-path dist/my-app

# 构建分析
ng build --stats-json

7.2 构建输出 #

text
dist/my-app/
├── browser/
│   ├── index.html
│   ├── main.[hash].js
│   ├── polyfills.[hash].js
│   ├── styles.[hash].css
│   └── assets/
└── server/                  # SSR输出

7.3 环境配置 #

bash
# 使用开发环境
ng serve

# 使用生产环境
ng serve --configuration production

# 构建指定环境
ng build --configuration staging

八、总结 #

文件/目录 作用
src/app/ 应用源代码
src/assets/ 静态资源
src/environments/ 环境配置
angular.json Angular CLI配置
package.json 项目依赖配置
tsconfig.json TypeScript配置

下一步:组件概述

最后更新:2026-03-26