[Go/Vue] 如何将Go全栈项目的前端部分托管到后端

403 阅读2分钟

一、前端部分

1. 配置vue.config.js

在前端部分的根目录下新建vue.config.js文件,并配置输出文件操作

// defineConfig 是 vue 提供的帮手函数,具有提示功能
const { defineConfig } = require("@vue/cli-service");

module.exports = defineConfig({
  transpileDependencies: true,
  //关闭eslint校验
  lintOnSave: false,

  //后台页面统一部署到 '/admin/' url下,这意味着后台页面访问时 url 为'http://www.xxx.com/admin/yyyyyyy'
  publicPath: "/admin/",

  //存放打包结果的目录
  outputDir: "dist",

  //存放图片、音频等静态资源的目录
  assetsDir: "static",
});

publicPath会让前端部分的页面最终展示在http://www.xxx.com/admin/xxxyyyzzz下,
因此之前在router/index.js中,以及组件中所有使用到路由跳转函数this.$router.push(...)的地方都要修改.

2. 修改相应路由路径

不必再在路由中添加/admin/前缀,以下举一个修改例子: image.png

3.使用yarn打包

package.json提供了相应打包命令:

// package.json

  "scripts": {
    "serve": "vue-cli-service serve",  //启动服务器
    "build": "vue-cli-service build",  //开始打包
    "lint": "vue-cli-service lint"     //校验格式约束
  },

我使用的包管理器是yarn,执行yarn build(npm使用npm run serve),可以发现多出一个文件夹,打包结果存储在此:

image.png

二、后端部分

1.新建文件夹static/,以存放前端打包文件

由于前端页面admin部分将被托管到后端,因此在后端根目录下新建文件夹static/admin,并将打包好的文件复制到此:

image.png

2.在ginrouter.go中配置,以托管资源

打包好的文件中已经有index.html,是用户访问前端页面的入口,也是后端托管前端页面的入口,

  • 使用r.LoadHTMLGlob()导入入口文件地址
  • 使用r.Static(relativePath,root)导入静态文件
package routers

import ...

// InitRouter router 入口文件
func InitRouter() {
   //先设置setMode(),再创建 gin.New() 才能正确运行配置
   gin.SetMode(utils.AppMode)

   r := gin.New()
   r.Use(middleware.Logger())
   r.Use(gin.Recovery())
   r.Use(middleware.Cors())

   //前端资源托管(pattern 参数 从项目根目录开始)
   r.LoadHTMLGlob("static/admin/index.html")
   //第1个参数是路由的路径,第2个参数是文件的路径
   r.Static("admin/static", "static/admin/static")
   //在浏览器地址栏输入localhost:<socket>/admin 即可访问Vue Router设置 path 为 '/' 的 component
   r.GET("admin", func(c *gin.Context) {
      c.HTML(200, "index.html", nil)
   })

...配置路由项...
}

三、配置完成

访问前端页面不再是之前的localhost:8080端口,而是后端的localhost:3000/admin子域名:

image.png