Skip to content
返回部署

部署 Vue 3 应用

用 Vite 构建和部署 Vue 3 SPA,包括组合式 API、Pinia 状态和 Vue Router。

平台入门

为什么

Vue 3 配 Vite 生成高度优化的静态包,开发 HMR 快,生产构建摇树优化。生态(Pinia、Vue Router)轻量,可部署到任何静态主机。

平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。

何时使用

渐进增强、管理工具和熟悉模板语法的团队选 Vue 3。需要 SSR/SEO 时用 Nuxt。

如何做

1. 构建 — npm run build 输出 dist/ 含 index.html + assets/ 2. Base URL — vite.config base 用于子路径部署 3. 路由 history — createWebHistory 需服务器 SPA 回退 4. 部署 — 上传 dist/ 到任何静态主机(Vercel/Netlify/S3) 5. 环境变量 — import.meta.env.VITE_* 构建时 6. 压缩 — 主机对 JS/CSS 启用 Brotli/Gzip

示例

// vite.config.ts import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; export default defineConfig({ plugins: [vue()], base: "/app/", build: { target: "es2020", cssCodeSplit: true }, }); // router — history 模式需 SPA 回退 import { createRouter, createWebHistory } from "vue-router"; const router = createRouter({ history: createWebHistory("/app/"), routes: [/* ... */], }); // vercel.json — SPA 回退 { "rewrites": [{ "source": "/app/(.*)", "destination": "/app/index.html" }] }

常见问题

  • ⚠刷新路由 404 — createWebHistory 未配服务器 SPA 回退
  • ⚠子路径部署资源 404 — base 未设为匹配部署路径
  • ⚠导航丢 Pinia 状态 — store 未用 pinia-plugin-persistedstate 持久化

最佳实践

  • ✓无重写能力的纯静态主机用 createWebHashHistory(哈希路由)
  • ✓vite rollupOptions 启用 manualChunks 分割大 vendor 依赖
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答