You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue Vite中部署静态页面?(Vuetify3+Firebase场景)

在Vite中托管独立静态HTML页面并配合Vue Router重定向的实现方法

1. 放置静态文件

和Vue CLI逻辑一致,直接把你的welcome静态页(含index.html、自定义JS、CSS等)放到项目根目录的public/welcome/文件夹下。例如:

  • public/welcome/index.html:落地页主HTML文件
  • public/welcome/style.css:落地页自定义样式
  • public/welcome/script.js:落地页自定义脚本

注意:HTML里引用资源时,用根路径(如/welcome/style.css)或相对路径(如./style.css)均可,Vite构建时会完整复制public目录下的所有文件到dist根目录,路径不会被修改。

2. 配置Vue Router的重定向逻辑

由于/welcome是静态HTML而非Vue组件,不能让Vue Router拦截该路径,需通过路由守卫直接引导浏览器访问静态资源:

路由配置与全局守卫(示例)

在你的路由配置文件(如src/router/index.js)中添加如下逻辑:

import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '../views/Dashboard.vue'

// 替换为你实际的Firebase认证判断逻辑
const isAuthenticated = () => {
  return !!window.firebase?.auth()?.currentUser
}

const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  // 其他需要认证的路由...
  {
    path: '/welcome',
    beforeEnter: (to, from, next) => {
      if (isAuthenticated()) {
        next('/') // 已认证用户跳回主应用
      } else {
        // 未认证直接跳转静态页,避免Vue Router接管
        window.location.href = '/welcome'
        next(false)
      }
    }
  },
  // 404路由:未认证重定向到welcome,已认证重定向到主页
  {
    path: '/:pathMatch(.*)*',
    redirect: () => isAuthenticated() ? '/' : '/welcome'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫,保护需要认证的路由
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    window.location.href = '/welcome'
    next(false)
  } else {
    next()
  }
})

export default router

3. 配置Firebase Hosting避免静态页被SPA接管

Firebase Hosting默认会把所有请求重写到index.html(适配SPA),这会导致/welcome路径被指向Vue入口文件。需在firebase.json中添加重写规则,排除/welcome路径:

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "!/welcome/**",
        "destination": "/index.html"
      }
    ]
  }
}

该规则表示:所有不是以/welcome/开头的请求才重写到index.html;/welcome/开头的请求直接返回对应的静态文件。

4. 构建与验证

执行npm run build后,public/welcome下的文件会完整复制到dist/welcome目录。部署dist目录到Firebase Hosting后:

  • 未认证用户访问需登录的路由时,会被重定向到/welcome静态页
  • 已认证用户访问/welcome会被跳回主应用
  • 静态页的自定义JS和CSS可正常加载

内容的提问来源于stack exchange,提问作者starleaf1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:52:46