在 SpringBoot 中部署 vue 工程(hash 模式)
前端打包设置
路由使用 createWebHashHistory()
js
const router = createRouter({
history: createWebHashHistory(),
routes: routes,
strict: true,
})
vite.config.js 中修改 base 路径
js
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
base: env.VITE_PUBLIC_PATH,
// 这里省略了其它配置参数
}
在 .env 配置文件中配置路径。比如:
准备把打包后的 dist 里面的文件部署到 spring boot 工程的 src/main/resources/static/vita 目录下,则配置为:/vita/
配置的值需要和 src/main/resources/static/vita 目录的名称保持一致。
但为了不影响开发环境的使用,需要开发环境和生产环境配置不同的值。
.env.production 配置:
shell
VITE_PUBLIC_PATH = /vita/
.env.development 配置:
shell
VITE_PUBLIC_PATH = /
修改 public 文件夹下的资源在 index.html 中的引用
一般情况下,在引用 public 目录下的资源时,使用 / 开头,比如:/favicon.svg
html
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
这在开发环境下是没问题的,但部署到 spring boot 中时,就需要 .env 配置文件中添加 VITE_PUBLIC_PATH 中配置的前缀。
可使用 %VITE_PUBLIC_PATH% 来引用 .env 文件中配置的项。
html
<link rel="icon" type="image/svg+xml" href="%VITE_PUBLIC_PATH%favicon.svg" />
前端打包 dist 文件夹
使用 vue-cli 打包 vue 前端项目后,生成的打包后的前端项目目录结构如下:
txt
dist
css
js
favicon.svg
index.html
注:后端不需要引入 spring-boot-starter-thymeleaf,没必要引入多余的 jar。
后端部署
将上面打包后的 dist 目录里面的内容,复制到 spring boot 项目的 resources/static/vita 目录下,目录结构如下:
txt
resources
static
vita
css
js
favicon.svg
index.html
启动 spring boot 项目,现在的访问页面是:http://localhost:8080/vita/index.html
但是我们想直接访问一个更简单的 url:http://localhost:8080
这时候我们需要在后端增加一些代码来处理。
java
package com.github.mengweijin.vita.framework.mvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Meng Wei Jin
**/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 重定向:registry.addViewController("/").setViewName("/vita/index.html");
* 转发:registry.addRedirectViewController("/", "/vita/index.html");
*
* @param registry ViewControllerRegistry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 将根路径 "/" 的请求转发到 "/vita/index.html"
registry.addViewController("/").setViewName("forward:/vita/index.html");
}
}