整合Angular2的问题在于,修改前端源码后,需要即时生效,总不能每次修改都ng build
吧,效率太低。
ng build
支持-w
参数,加上后可以一直运行,检测文件变化后重新build,我们就利用这个特性来配置idea。当然,如果你不嫌麻烦,可以在每天写代码前先在终端里执行ng build -w
。
先看配置好后的项目结构:
angular开发目录在src/main目录下,其实这个目录放哪都行,因为这里不是最终执行的代码。为了保护源代码,不建议放到webapp目录下。
dist目录才是angular编译生成的最终代码,访问路径 http://localhost:8080/dist/
配置步骤
先配置SpringMVC环境,或者可以直接下载SpringMVCModuleDemo ,在Intellij Idea中打开。
打开终端,切到
web/src/main
目录下
执行ng new angular --routing --skip-install
routing参数是自动创建路由模块,skip-install
是不自动执行npm install
下载依赖模块,因为用淘宝cnpm更快。切到刚创建的angular目录,执行
cnpm install
下载依赖编辑 angular目录下的package.json,添加两个script,develop和release:
{ "name": "angular", "version": "0.0.0", "license": "MIT", "angular-cli": {}, "scripts": { "ng": "ng", "start": "ng serve", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "develop":"ng build -op ../webapp/dist -bh /dist/ -w", "release":"ng build -op ../webapp/dist -bh /dist/ -prod -aot --env=prod" }, ... }
develop用于开发过程中,自动监控文件变化,一旦有文件修改,自动rebuild,覆盖webapp/dist目录下生成的文件。
release用于正式发布,build时启用aot,可大幅缩小代码体积。同时使用
environments/environment.prod.ts
里的配置,切换到正式环境添加运行配置
在Run/Debug Configurations
(Run-Edit Configurations)窗口,添加一个npm配置:release只有发布时才使用一次,加不加都无所谓
修改路由策略
Angular路由默认使用了PathLocationStrategy
,使得路径看起来像是访问真正存在服务器上的文件,但是这个模式需要web容器将所有文件都转发到index.html上,我目前没找到jetty的相关配置。所以,在开发阶段,暂时使用HashLocationStrategy
这种兼容模式,路径用#
隔开。
配置app-routing.module.ts
:import {NgModule} from "@angular/core"; import {Routes, RouterModule} from "@angular/router"; import {UserListComponent} from "./user/user-list/user-list.component"; import {UserDetailComponent} from "./user/user-detail/user-detail.component"; const routes: Routes = [ { path: 'user/list', component:UserListComponent, children: [] }, { path:'user/:id', component:UserDetailComponent, } ]; @NgModule({ imports: [RouterModule.forRoot(routes,{ useHash: true })], exports: [RouterModule], providers: [] }) export class AppRoutingModule { }
重点在
RouterModule.forRoot
,{ useHash: true }
git忽略dist目录
因为dist里所有文件都是Angular生成的,我们不需要维护到git上,在.gitignore
里将dist目录加上,添加一行:/web/src/main/webapp/dist/
如果之前已经跟踪之个目录,执行下面的命令取消:
git rm --cached -r web/src/main/angular/
使用maven插件执行angular build
在web模块的pom.xml里,使用exec-maven-plugin插件构建angular代码<build> <finalName>web</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.5.0</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>exec</goal> </goals> </execution> </executions> <configuration> <executable>cnpm</executable> <workingDirectory>${basedir}/src/main/angular </workingDirectory> <arguments> <argument>run</argument> <argument>release</argument> </arguments> </configuration> </plugin> </plugins> </build>
如何使用
开发过程中:
打开项目后,在工具栏上选中AngularBuilder启动配置,点运行图标。启动后AngularCLI会一直在后台监控文件变化。再切到WebServer,启动Jetty即可。
因为build需要时间,改完angular代码后可能需要几秒钟后刷新页面才能看到效果,在底部的Run窗口可以看到日志输出。
发布:
mvn package
一条命令即可,maven会在打包过程中执行cnpm run release
命令,构建angular代码