使用 vite-plugin-dynamic-base 实现运行时动态设置上下文路径

发布于:2025-05-22 ⋅ 阅读:(18) ⋅ 点赞:(0)

我们一般会在编译之前设置上下文,那么如何在编译之后动态设置上下文的路径?

本文使用的技术栈是 Go(Gin) + Vue.js(Vite)

本文使用到的第三方包:https://github.com/chenxch/vite-plugin-dynamic-base

配置 vite.config.ts

import { dynamicBase } from 'vite-plugin-dynamic-base'

export default defineConfig({
  // base: "/",
  base: process.env.NODE_ENV === "production" ? "/__dynamic_base__/" : "/",
  plugins: [
    dynamicBase({ /* options */ }),
  ],
})

后端动态返回 index.html 的内容,比如我后端使用 golang 实现

在返回内容前,对内容进行了处理,替换 __dynamic_base__ 为动态上下文,并且将 window.__dynamic_base__ 设置为动态上下文

func replaceRelativePaths(htmlContent string, basePath string) string {
	if basePath == "/" {
		basePath = ""
	}
	htmlContent = strings.ReplaceAll(htmlContent, "/__dynamic_base__/", basePath+"/")
	injection := fmt.Sprintf(`
	<script>
		window.__dynamic_base__ = "%s";
	</script>`, basePath)
	return strings.Replace(htmlContent, "</head>", injection+"</head>", 1)
}

最终效果如下(这里设置的上下文是 /abc):

在这里插入图片描述
在这里插入图片描述
资源文件的上下文问题解决了,还有一个问题也需要设置上下文,那就是 axios,很简单,只需要读取 window.__dynamic_base__ 就可以了。

const dynamicBase = (window as any).__dynamic_base__ || "";
// 创建 axios 实例
const service = axios.create({
  baseURL: `${dynamicBase}${import.meta.env.VITE_APP_BASE_API}`,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

这样我们就实现了,真正意义上的动态设置项目全局上下文


网站公告

今日签到

点亮在社区的每一天
去签到