Vue打包整合到SpringBoot项目时遇到 js 和 Css 404的问题

当使用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/");
    }
}

就可以成功运行
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值