Vite + Vue3 多页面应用 (MPA) 完整教程

Gary Chen
Vite + Vue3 多页面应用 (MPA) 完整教程

Vite + Vue3 多页面应用 (MPA) 完整教程

本教程将详细介绍如何使用 Vite 和 Vue3 配置多页面应用(MPA),解决路由刷新 404 问题,并实现高效开发。

一、项目初始化

1. 创建项目

npm create vite@latest vite-mpa-demo --template vue
cd vite-mpa-demo
npm install

2. 安装必要依赖

npm install vue-router@4 connect-history-api-fallback --save-dev

二、项目结构配置

vite-mpa-demo/
├── admin.html                # 管理后台入口
├── index.html                # 主应用入口
├── src/
│   ├── admin/                # 管理后台代码
│   │   ├── main.js           # 管理后台入口文件
│   │   ├── App.vue           # 管理后台根组件
│   │   └── router.js         # 管理后台路由
│   ├── main/                 # 主应用代码
│   │   ├── main.js           # 主应用入口文件
│   │   ├── App.vue           # 主应用根组件
│   │   └── router.js         # 主应用路由
│   └── shared/               # 共享代码
├── vite.config.js            # Vite 配置文件
└── package.json

三、核心配置文件

1. vite.config.js 完整配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import history from 'connect-history-api-fallback'

export default defineConfig({
  plugins: [
    vue(),
    {
      name: 'custom-mpa-rewrite',
      configureServer(server) {
        server.middlewares.use(
          history({
            rewrites: [
              { from: /^\/admin(\/.*)?$/, to: '/admin.html' },
              { from: /^\/app(\/.*)?$/, to: '/app.html' },
              { from: /./, to: '/index.html' }
            ],
            htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
            disableDotRule: true,
            verbose: true
          })
        )
      }
    }
  ],
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        admin: resolve(__dirname, 'admin.html'),
        app: resolve(__dirname, 'app.html')
      },
      output: {
        chunkFileNames: 'assets/[name]-[hash].js',
        entryFileNames: 'assets/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash][extname]'
      }
    }
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    open: '/index.html',
    fs: {
      strict: false
    }
  }
})

2. HTML 入口文件示例

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Main Application</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/main/main.js"></script>
</body>
</html>

admin.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Admin Panel</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/admin/main.js"></script>
</body>
</html>

四、路由配置

1. 主应用路由 (src/main/router.js)

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../shared/views/Home.vue')
    },
    {
      path: '/about',
      name: 'About',
      component: () => import('../shared/views/About.vue')
    }
  ]
})

2. 管理后台路由 (src/admin/router.js)

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
  history: createWebHistory('/admin'),
  routes: [
    {
      path: '/',
      name: 'Dashboard',
      component: () => import('../shared/views/Dashboard.vue')
    },
    {
      path: '/users',
      name: 'UserManagement',
      component: () => import('./views/Users.vue')
    }
  ]
})

五、应用入口文件

1. 主应用入口 (src/main/main.js)

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

2. 管理后台入口 (src/admin/main.js)

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

六、开发与构建

1. 开发模式

npm run dev

访问:

  • 主应用: http://localhost:3000/
  • 管理后台: http://localhost:3000/admin/

2. 生产构建

npm run build

构建结果将输出到 dist 目录,包含:

dist/
├── assets/
│   ├── main-xxxxxx.js
│   ├── admin-xxxxxx.js
│   └── ...
├── index.html
├── admin.html
└── app.html

七、生产环境部署

Nginx 配置示例

server {
  listen 80;
  server_name yourdomain.com;

  location / {
    root /path/to/dist;
    try_files $uri $uri/ /index.html;
  }

  location /admin {
    root /path/to/dist;
    try_files $uri $uri/ /admin.html;
  }

  location /app {
    root /path/to/dist;
    try_files $uri $uri/ /app.html;
  }
}

八、常见问题解决

1. 刷新页面 404

  • 确保 vite.config.js 中的 historyApiFallback 配置正确
  • 检查路由的 createWebHistory 基路径是否匹配

2. 静态资源加载失败

  • 使用绝对路径引用资源:/src/assets/logo.png
  • 检查构建后的资源路径是否正确

3. 热更新不工作

  • 确保所有入口文件在 rollupOptions.input 中正确定义
  • 检查浏览器控制台是否有 HMR 连接错误

九、高级优化

1. 共享代码配置

vite.config.js 中添加优化配置:

optimizeDeps: {
  include: ['vue', 'vue-router', 'shared-components']
}

2. CSS 独立打包

build: {
  cssCodeSplit: true,
  rollupOptions: {
    output: {
      assetFileNames: 'assets/[name]-[hash][extname]'
    }
  }
}

通过本教程,你可以构建一个完整的 Vite + Vue3 多页面应用,解决开发环境下的路由刷新问题,并实现高效的生产部署。