springboot项目vue前端运行
时间: 2025-04-16 18:08:05 浏览: 25
### 配置和运行 Vue.js 前端
#### 使用 Maven 或 Gradle 构建工具集成前端资源
为了使 Spring Boot 和 Vue.js 能够协同工作,在同一个 Git 仓库中管理两者是一个常见的做法。当采用这种方式时,通常会利用构建工具如Maven或Gradle来处理整个项目的编译、测试以及部署过程[^1]。
对于基于 Maven 的项目而言,可以在 `pom.xml` 文件内加入插件支持前端工程化的流程:
```xml
<build>
<plugins>
<!-- 执行 npm install 及 build -->
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.12.0</version>
<configuration>
<workingDirectory>${project.basedir}/src/main/vue</workingDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals><goal>install-node-and-npm</goal></goals>
<phase>generate-resources</phase>
<configuration>
<nodeVersion>v16.13.0</nodeVersion>
<npmVersion>8.1.0</npmVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals><goal>npm</goal></goals>
<phase>generate-resources</phase>
<configuration>
<arguments>ci</arguments>
</configuration>
</execution>
<execution>
<id>npm run build</id>
<goals><goal>npm</goal></goals>
<phase>compile</phase>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</ executions >
</ plugin >
</ plugins >
</ build >
```
这段配置使得每次执行 Maven 编译命令时都会先安装 Node.js 环境并完成 Vue 应用程序的打包操作。
#### 设置静态文件路径
为了让 Spring Boot 正确识别由 Vue CLI 生产模式下生成的静态 HTML/CSS/JS 文件作为应用程序入口点之一,需调整 application.properties 中关于静态资源位置的相关设置:
```properties
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
```
这允许访问位于 classpath 下指定目录中的任何静态资产,而这些正是经过 vue-cli-service 构建之后所放置的地方。
#### 启动类配置
最后一步是在主启动类上添加 @CrossOrigin 注解以便跨域资源共享(CORS),从而让前后端能够顺利通信;同时也可以考虑引入 spring-boot-starter-thymeleaf 来提供模板解析服务,即使最终页面是由单页应用(SPA)框架渲染出来的也不例外:
```java
@SpringBootApplication
@CrossOrigin(origins = "*") // 开发阶段可暂时设为通配符,生产环境建议改为具体域名列表
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
```
以上就是如何在一个Spring Boot项目里边配置和运行Vue.js前端的方法概述。
阅读全文
相关推荐




















