Để tạo Angular và Spring Boot app trong một bạn phải tạo build angular và copy nó vào target/classes/static của spring boot. Bạn có thể đổi output của angular app build ở angular.json. Bài viết này sẽ hướng dẫn các bạn automate tất cả các công đoạn bằng tools:
- Tạo spring boot project (bằng spring initalizier trang chủ, vscode hay intellij)
- Thêm plugin com.github.eirslett::frontend-maven-plugin
- Config plugin: node version bạn muốn dùng cho project và các executions. Ở đây mình sẽ thêm execution download node:
<plugin>
...
<configuration>
<nodeVersion>v18.16.0</nodeVersion>
</configuration>
<executions>
<execution>
<id>Install Node and NPM</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
</execution>
</executions>
</plugin>
- Chạy goal để nó tải local node về. Tạo bash script (ví dụ tên: npm) để chạy node local đó
#!/bin/sh
cd $(dirname $0)
PATH="$PWD/node/":$PATH
node "node/node_modules/npm/bin/npm-cli.js" "$@"
- Sau đó chạy ./npm init -y để khởi tạo node project. Sau đó tải @angular/cli local về bằng ./npm install @angular/cli. Nếu bạn không khởi tạo node project trước mà tải cli luôn thì nó sẽ tải ra ngoài cái spring boot project của bạn.
- Tạo script để chạy cái cli local đó (ví dụ tên: ng):
#!/bin/sh
cd $(dirname $0)
PATH="$PWD/../node/":"$PWD":$PATH
../node_modules/@angular/cli/bin/ng.js "$@"
- Dùng script này để tạo angular project: ./ng new client (client là tên của project).
- cd vào frontend project, tạo 2 cái script npm and ng script để build cái frontend project, nhớ thay đổi path đến exe file (ở đây là node.js và ng.js) rồi chạy script bằng lệnh để build. Nếu build thành công thì xóa nó, đổi output như đề cập ban đầu và build lại. Chạy spring boot bạn sẽ thấy ứng dụng angular serve ở localhost:8080
- Thêm executions vào plugin để automate mấy công đoạn install angular cli và angular app dependencies lằng nhằng bên trên
<execution>
<id>Install Angular CLI</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>Install dependencies from client/package.json</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install ./client</arguments>
</configuration>
</execution>
<execution>
<id>Build Angular Application</id>
<goals>
<goal>
npm
</goal>
</goals>
<configuration>
<arguments>--prefix ./client run-script build</arguments>
</configuration>
</execution>
- Giờ bạn có thể clean tất cả các thứ (node local, angular cli local và angular dependencies npm install) và chạy lại spring-boot:run goal bằng intellij hoặc lệnh ./mvnw springboot:run để thấy mọi thứ lại build lại như cũ.
- Chạy thêm lệnh ./npm run watch để rebuild khi có change ở frontend app.
Tham khảo thêm: github source code