Vue打包整合到SpringBoot项目时遇到 js 和 Css 404的问题
当使用Vue 和SpringBoot 分别开发前后端,而需要整合部署到同一个项目时,往往会遇到一些奇奇怪怪的问题,出现一些很烦人的错误。本篇文章通过结合自己实践的经验,简单的介绍一下Vue 和SpringBoot整合打包的流程以及出现典型问题的解决方式。1、首先是通过npm run build 打包Vue 项目一般来说可以用默认的设置,直接打包,也可以进行自己的一些修改对于Vue 2.0 来说,可
当使用Vue 和SpringBoot 分别开发前后端,而需要整合部署到同一个项目时,往往会遇到一些奇奇怪怪的问题,出现一些很烦人的错误。本篇文章通过结合自己实践的经验,简单的介绍一下Vue 和SpringBoot整合打包的流程以及出现典型问题的解决方式。
1、首先是通过 npm run build 打包Vue 项目
一般来说可以用默认的设置,直接打包,也可以进行自己的一些修改
对于Vue 2.0 来说,可以通过编辑config/index.js来修改配置
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
而Vue 3.0需要在vue.config.js 中编辑配置
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? './' : './',
outputDir: 'dist',
assetsDir: 'static'
}
执行打包
npm run build
当出现 Build complete.表示打包完成
Build complete.
Tip: built files are meant to be served over an HTTP server.
Opening index.html over file:// won't work.
2、将打包的Vue项目放置在SpringBoot的后端项目中
打开Vue项目,可以看到在dist文件夹下已经生成了Static文件夹
和index.html页面
Ctrl + c复制生成的这两个文件,Ctrl + v 粘贴到后端项目的resources文件夹下
注意:
将index.html放置在Static中,其他保持不变,如图所示
3、配置addResourceHandler和addResourceLocations映射静态资源地址
继承WebMvcConfigurer 类,重写addResourceHandlers 方法
如果访问路径是addResourceHandler中的 /static/** 这个路径 那么就 映射到访问本地的addResourceLocations 的参数的这个 /static/ 路径上,这样就可以让别人访问服务器的本地文件了,比如本地图片或者本地音乐视频什么的。
详见Spring Boot 中自定义静态资源映射目录
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Mi
* @version 1.0
* @description: TODO
* @date 2022/4/17 9:47
*/
@Configuration
public class SpringWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
就可以成功运行
更多推荐
所有评论(0)