Spring Boot 打包集成前端项目

前言

  对于前后端分离大家都不陌生,自己也参与了很多中后台方面的前后端分离项目,通常我们的开发套路都是一个前端项目、一个后端项目,通过API接口进行通讯,会话采用token方式,发布时将前端发布到nginx、后端发布servlet容器,这种部署方式比较常见也比较常见和流行,自己前期搭建的一些框架都是采用的这种方式,随着使用,我发现存在一些问题,首先是复杂度方面,其次还有安全方面,由于token的无状态性并不适合中后台项目,见文(译)别再使用 JWT 作为 Session 系统!问题重重且很危险。 ,而且危险重重。

  目前个人更倾向的于采用API接口方式进行数据通讯,采用session方式来作为中后台会话管理方案,前端配置使用hash路由方式,将前端代码编译打包后放入Spring Boot静态目录,安全框架使用Spring SecuritySpring Security提供了基于session的强大的会话管理和安全控制功能。
  但是如果每次都手动进行前端项目编译打包,然后手动copy到后端静态目录下,繁琐麻烦,那如果通过maven打包时,自动将前端代码编译并copytarget下的静态目录下,这样打包成jarwar,或者docker镜像,前端页面都会被包含进来,想法是好的,经过钻研,想法实现了,废话不说,上步骤。

步骤

将前端项目移动到后端/src/main目录下

  如图,console-fe 为前端项目。

添加frontend-maven-plugin插件

  frontend-maven-plugin 可以为项目本地下载/安装NodeNPM,运行npm命令 。还可以运行BowerGruntGulpJspmKarmaWebpack的任意组合 。可以在WindowsOS XLinux上运行。

GitHubfrontend-maven-plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<build>
...
<!--编译打包前端项目-->
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.10.4</version>
<configuration>
<installDirectory>target</installDirectory>
<workingDirectory>src/main/console-fe</workingDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<nodeVersion>v14.15.1</nodeVersion>
<nodeDownloadRoot>http://npm.taobao.org/mirrors/node/</nodeDownloadRoot>
<npmDownloadRoot>https://mirrors.huaweicloud.com/npm-software/v4.4.3.tar.gz
</npmDownloadRoot>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>install</arguments>
<npmRegistryURL>https://registry.npm.taobao.org</npmRegistryURL>
</configuration>
</execution>
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>
<!--清理,clean的时候,清除dist目录-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<configuration>
<filesets>
<fileset>
<directory>src/main/console-fe/dist</directory>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>
...
</build>

配置资源映射

  将npm run build 后的 dist 内容复制到 resources 目录下

1
2
3
4
5
6
7
8
9
10
11
12
<build>
...
<resources>
<!-- 将 npm run build 后的 dist 内容复制到 resources 目录下 -->
<resource>
<directory>src/main/console-fe/dist</directory>
<targetPath>resources</targetPath>
</resource>
</resources>
...
</build>

测试

执行 mvn clean && mvn package 命令

查看 target 目录下 resources

Spring Boot 打包集成前端项目

https://pingfangushi.com/posts/3340/

作者

SanLi

发布于

2021-07-08

更新于

2021-07-08

许可协议