将 Vue 项目打包后部署到 Spring Boot 项目中的全面指南

news/2025/2/24 0:48:36

将 Vue 项目打包后部署到 Spring Boot 项目中的全面指南

在现代 Web 开发中,前后端分离架构已经成为主流。然而,在某些场景下,我们可能需要将前端项目(如 Vue)与后端项目(如 Spring Boot)集成部署。

本文将详细介绍如何将 Vue 项目打包后部署到 Spring Boot 项目中,包括必要的配置步骤和注意事项。

目录

  • 将 Vue 项目打包后部署到 Spring Boot 项目中的全面指南
    • 项目概述
    • 前提条件
    • 步骤一:配置 Vue 项目
      • 1.1 修改 `vite.config.js` 文件
      • 1.2 打包 Vue 项目
    • 步骤二:搭建 Spring Boot 项目
      • 2.1 创建 Maven 项目
      • 2.2 修改 `pom.xml` 文件
      • 2.3 配置 `application.yml` 文件
      • 2.4 编写启动类
      • 2.5 编写跳转控制器
    • 步骤三:整合 Vue 项目到 Spring Boot 项目
      • 3.1 创建静态资源和模板目录
      • 3.2 复制 Vue 打包文件到 Spring Boot 项目
      • 3.3 修改 `index.html` 中的资源路径
    • 步骤四:启动并测试
    • 附加配置:修改前端后端服务地址
    • 附加配置:修改前端 URL 转发
    • Nginx配置[可选]
      • 1.基本思路
      • 2.示例配置
      • 3.重启
      • 4.Vite配置
    • 常见问题及解决方案
    • 总结

项目概述

本文将指导你如何将一个基于 Vue 3 的前端项目打包后,部署到一个基于 Spring Boot 的后端项目中。通过这种方式,你可以将前后端项目集成在一个应用中,简化部署流程。

前提条件

  • 已安装 Node.js 和 npm
  • 已安装 Java 和 Maven
  • 已安装 Spring Boot 和 Vue CLI 或 Vite(本文以 Vite 为例)
  • 基本的 Java 和 JavaScript 知识

步骤一:配置 Vue 项目

1.1 修改 vite.config.js 文件

为了确保 Vue 项目在打包后能够正确引用静态资源,需要修改 vite.config.js 文件,添加 base:'./' 配置。

// vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  base: './'
})

1.2 打包 Vue 项目

在 Vue 项目根目录下运行以下命令进行打包:

npm run build

打包完成后,会在项目根目录下生成一个 dist 文件夹,里面包含了编译后的静态文件。

在这里插入图片描述

步骤二:搭建 Spring Boot 项目

2.1 创建 Maven 项目

使用 Maven 创建一个新的 Spring Boot 项目。你可以使用 Spring Initializr 来快速生成项目结构。

2.2 修改 pom.xml 文件

pom.xml 中添加必要的依赖,包括 spring-boot-starter-thymeleafspring-boot-starter-web

<!-- pom.xml -->
<dependencies>
    <!-- Thymeleaf [可选,不建议]-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <!-- Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2.3 配置 application.yml 文件

src/main/resources 目录下创建或修改 application.yml 文件,配置 Thymeleaf 和静态资源路径
[可以不用Thymeleaf模板引擎]

# application.yml
server:
  port: 8080

spring:
  web:
    resources:
      static-locations: classpath:/static/, classpath:/public/, classpath:/resources/,classpath:/META-INF/resources/
  mvc:
    static-path-pattern: /**
    # 实测用了Thymeleaf会导致vue某些布局出现一点点问题,建议不用
#    thymeleaf:
#      mode: HTML
#      cache: false
#      prefix: classpath:/templates/

2.4 编写启动类

创建主启动类 Main.java

// src/main/java/demo/Main.java
package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

2.5 编写跳转控制器

创建控制器 PageController.java 以处理页面跳转:

// src/main/java/jkw/controller/PageController.java
package jkw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
    // 前台页面
    @RequestMapping("/")
    public String FrontIndex() {
        return "forward:./index.html";
        // 重定向到前端首页
    }
}

步骤三:整合 Vue 项目到 Spring Boot 项目

3.1 创建静态资源和模板目录

src/main/resources 目录下创建 statictemplates[不用Thymeleaf可以不创建templates] 文件夹,分别存放静态文件和动态页面。

3.2 复制 Vue 打包文件到 Spring Boot 项目

将 Vue 项目 dist 文件夹中的 assetsfavicon.ico 文件复制到 static/ 目录下。

dist 文件夹中的 index.html 复制到 templates/ 目录下。

3.3 修改 index.html 中的资源路径

打开 index.html,修改资源引用路径:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
    <script type="module" crossorigin src="/assets/index-1973819a.js"></script>
    <link rel="stylesheet" href="/assets/index-4afc3c58.css">
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

确保所有资源路径都以 / 开头,这样 Spring Boot 才能正确找到静态资源。

步骤四:启动并测试

启动 Spring Boot 项目:

mvn spring-boot:run

在浏览器中访问 http://localhost:8080/,你应该能够看到 Vue 项目的页面。

附加配置:修改前端后端服务地址

在 Vue 项目的 .env.development 文件中,修改 TARGET 为正式环境后端服务 API 根地址:

# just a flag
ENV = 'development'

# backend api
TARGET = 'http://localhost:9000/'

附加配置:修改前端 URL 转发

  1. 方法一
    修改 .env 文件,将 VUE_APP_BASE_API 设置为空:
# base api

#VUE_APP_BASE_API = '/api'

VUE_APP_BASE_API = ''

原因:前后端独立部署时,前端会有一个转发配置 vue.config.js。但当部署到 Spring Boot 后,这个转发配置就无效了,必须将其去掉,否则所有对后端的请求都会带着 api 前缀,导致 404 错误。

  1. 方法二
  • 也可以通过Nginx伪静态控制后端接口往/api转发到本地8080

Nginx配置[可选]

1.基本思路

静态资源:由 Nginx 直接提供,路径为 /。
API 请求:所有以 /api 开头的请求被转发到后端 Spring Boot 服务(本地 8080 端口)。
其他请求:默认返回 Vue 应用的 index.html,由前端路由处理。

2.示例配置

假设你的 Vue 和 Spring Boot 项目都部署在同一个服务器上,Nginx 配置文件(通常位于 /etc/nginx/sites-available/default/etc/nginx/conf.d/your_site.conf)可以如下配置:

server {
    listen 80;
    server_name your_domain.com;  # 替换为你的域名或IP

    root /path/to/your/vue/dist;  # Vue 项目的 dist 目录
    index index.html index.htm;

    # 处理静态资源
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 仅转发以 /api 开头的请求到后端 Spring Boot 服务
    location ^~ /api/ {
        proxy_pass http://localhost:8080/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 可选:处理 WebSocket(如果需要)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # 可选:处理其他反向代理需求
    # location /other_proxy/ {
    #     proxy_pass http://other_service/;
    # }
}

3.重启

重新加载 Nginx 配置
在修改完 Nginx 配置文件后,测试配置是否正确:

sudo nginx -t

如果没有错误,重新加载 Nginx:

sudo systemctl reload nginx

4.Vite配置

  • Vite 配置调整
    为了确保前端 Vue 应用在构建时能够正确处理 API 请求的路径,需要调整 Vite 的配置。
  1. 修改 base 和 publicPath
    在 vite.config.js 中,设置 base 为 /,确保静态资源路径正确:
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: '/',  // 设置为根路径
  build: {
    // 可选:设置输出目录
    outDir: 'dist',
    // 可选:其他构建选项
  },
  // 其他配置...
})
  1. 配置代理(开发环境)
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: '/',
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',  // 后端 Spring Boot 服务地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')  // 可选:根据需要重写路径
      }
    }
  },
  // 其他配置...
})
  1. 配置代理(生产环境)
    在生产环境中,由于 Nginx 已经处理了 /api 的转发,因此无需在 Vite 配置中额外处理。但是,确保前端代码中的 API 请求路径以 /api 开头。例如:
// 示例:使用 Axios 进行 API 请求
import axios from 'axios'

axios.defaults.baseURL = '/api'

// 现在,所有 Axios 请求都会自动加上 /api 前缀
axios.get('/users')
  .then(response => {
    console.log(response.data)
  })

常见问题及解决方案

  1. *资源路径错误
  2. *:确保 index.html 中的资源路径正确,并且 Spring Boot 的静态资源路径配置正确。
  3. 跨域问题:如果前后端分离部署,需要配置 CORS 策略。
  4. 缓存问题:在开发过程中,清理浏览器缓存或使用无缓存模式进行测试。
  5. 权限问题:确保 Spring Boot 项目有权限访问 Vue 项目的静态资源。

总结

通过以上步骤,你可以将 Vue 项目打包后部署到 Spring Boot 项目中,实现前后端项目的集成。这种方式简化了部署流程,但也带来了一些挑战,如资源路径配置和静态资源管理。
根据具体需求,你可能需要进一步优化配置,例如使用 Spring Boot 的静态资源处理机制来管理前端资源,或者使用更复杂的构建工具来处理前端和后端的集成。


http://www.niftyadmin.cn/n/5863888.html

相关文章

行业分析---对自动驾驶规控算法未来的思考

1 前言 随着自动驾驶端到端大模型的兴起&#xff0c;小鹏、华为、理想、蔚来、小米等公司都对自动驾驶业务部进行了组织架构的调整&#xff0c;准备应对新的或者更高级别的自动驾驶研发任务。 近几年由于自动驾驶技术的快速发展&#xff0c;不少从业者觉得相关职业的未来充满了…

使用IDEA提交SpringBoot项目到Gitee上

登录Gitee并新建仓库 创建本地仓库 提交本地代码到本地仓库 提交本地代码到远程仓库

Redis 深度解析:高性能缓存与分布式数据存储的核心利器

在现代分布式系统中&#xff0c;性能与可扩展性是开发者面临的核心挑战之一。为了应对高并发、低延迟的需求&#xff0c;缓存技术成为了不可或缺的解决方案。而 Redis&#xff0c;作为一款开源的、基于内存的键值存储系统&#xff0c;凭借其卓越的性能、丰富的数据结构和高可用…

我用Ai学Android Jetpack Compose之LinearProgressIndicator

本篇&#xff0c;我们来学习LinearProgressIndicator&#xff0c;答案来自 通义千问 Q:我想学习LinearProgressIndicator&#xff0c;麻烦你介绍一下 当然可以&#xff01;LinearProgressIndicator 是 Jetpack Compose 中的一个组件&#xff0c;用于显示线性进度条。它非常适…

Java 中的 List 和 Map:全面解析与实际应用

在 Java 编程中&#xff0c;List 和 Map 是两种非常重要的数据结构&#xff0c;广泛应用于各种场景。它们提供了灵活的方式来存储和操作数据&#xff0c;能够帮助开发者更高效地实现业务逻辑。本文将深入解析 Java 中 List 和 Map 的定义与使用&#xff0c;并通过具体代码示例展…

ubuntu docker 安装 deepseek anythingllm/openwebui教程

全新服务器安装起始&#xff1a; 1. 安装ubuntu到服务器中 2. 安装docker 安装教程 ubuntu 安装 docker详细教程_ubuntu安装教程docker-CSDN博客 3. 安装 ollama docker pull ollama/ollama 3.1 创建 存储目录 &#xff08;示例放在/home/ollama中&#xff09; cd /home/ …

2025高维多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码

一、NMOPSO介绍 基于导航变量的多目标粒子群优化算法&#xff08;Navigation Variable-based Multi-Objective Particle Swarm Optimization, NMOPSO&#xff09;是一种专门用于无人机三维路径规划的先进算法。该算法通过将路径规划问题建模为一个多目标优化问题&#xff0c;并…

学习数据结构(11)二叉树(堆)下

1.堆的概念 如果有⼀个集合 K {k0&#xff0c;k1&#xff0c;k2&#xff0c;...&#xff0c;k(n-1)} &#xff0c;把它的所有元素按完全二叉树的形式存储在一个一维数组中&#xff0c;并满足&#xff1a;K(i)<2*i1且K(i)<2*i2&#xff08;K(i)>2*i1且K(i)>2*i2&a…