以下是为您重新整理的若依(RuoYi)前后端分离版改造为单体部署版的操作指南:
若依前后端分离版改造为单体部署指南
前言
本项目基于若依前后端分离版开发,现需将其改造为不分离版本,即将前端打包产物整合进后端 JAR 包中统一运行。以下是详细的改造步骤。
一、 修改前端项目配置
1. 修改生产环境配置
编辑 ruoyi-ui/.env.production 文件,配置 API 基础路径(二选一):
# 方式一:本机地址访问(推荐)
VUE_APP_BASE_API = '/'
# 方式二:指定任意地址访问
# VUE_APP_BASE_API = 'http://xxx.xxx.xxx.xxx:8080'
2. 修改路由模式
编辑 ruoyi-ui/src/router/index.js,将路由模式设置为 hash:
export default new Router({
mode: 'hash', // 必须改为 hash 模式
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
3. 修改注销跳转逻辑
编辑 ruoyi-ui/src/layout/components/Navbar.vue 中的 logout 方法,防止重定向错误:
async logout() {
this.$confirm('确定注销并退出系统吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$store.dispatch('LogOut').then(() => {
// 注意:跳转 index 前加 /#/ 防止定向错误
location.href = '/#/index';
})
}).catch(() => {});
}
4. 执行前端打包
在前端项目根目录运行以下命令生成 dist 文件:
npm run build:prod
二、 修改后端项目配置
1. 添加 Thymeleaf 模板引擎配置
编辑 ruoyi-admin/src/main/resources/application.yml:
spring:
# 模板引擎配置
thymeleaf:
mode: HTML
encoding: utf-8
cache: false
2. 添加 Thymeleaf 依赖
编辑 ruoyi-admin/pom.xml,引入模板引擎依赖:
<!-- spring-boot-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3. 配置静态资源映射
编辑 ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java,在 addResourceHandlers 方法中添加:
/** 前端静态资源配置 */
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
4. 放行静态资源访问权限
编辑 ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java,在 configure 方法中添加匿名访问规则:
// 静态资源可匿名访问,主要添加 "/static/**", "/index", "/*.ico"
.antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**", "/static/**", "/index", "/*.ico").permitAll()
5. 设置首页访问控制器
编辑 SysIndexController.java,配置根路径返回页面:
@RequestMapping("/")
public ModelAndView index() {
return new ModelAndView("index.html");
}
6. 整合前端静态资源
将前端打包生成的 dist 目录内容复制到后端项目中:
- HTML 文件:放入
ruoyi-admin/src/main/resources/templates/目录 - JS/CSS/图片等静态文件:放入
ruoyi-admin/src/main/resources/static/目录
注意:如果
templates或static目录不存在,请手动新建。
三、 启动验证
启动后端服务,访问测试地址(例如:http://192.168.164.134:8080/)。
✅ 成功标志:页面正常显示首页并加载出验证码,即表示改造完成。