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

Vue3 Vite配置:如何用不同命令启动不同应用并访问根路径

解决Vue3 + Vite多应用开发根路径访问问题

问题根源

你当前的客户应用Vite配置未指定开发模式下的默认入口根目录,导致启动后自动加载项目根目录的index.html,只能通过customers.html路径访问客户应用,进而引发Vue-Router的路由匹配异常。

解决方案

1. 调整客户应用的Vite配置文件(vite.config.customers.ts)

将配置的root指定为客户应用所在目录,同时适配路径规则:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  // 把客户应用目录设为Vite的根目录
  root: 'src/apps/customers-app',
  plugins: [vue()],
  resolve: {
    alias: {
      // 配置别名,方便引入项目根目录的公共资源
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    // 指定客户应用的构建输出目录,避免和后台应用混淆
    outDir: resolve(__dirname, 'dist/customers'),
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'src/apps/customers-app/index.html')
      }
    }
  },
  server: {
    port: 8080, // 可根据需求修改端口,若需同时启动两个应用,需设置不同端口
    open: true // 启动后自动打开根路径
  }
})

2. 优化package.json的scripts命令

简化启动命令,确保启动对应应用时直接映射到根路径:

"scripts": {
  "dev": "vite", // 启动后台管理应用,访问http://localhost:8080/
  "dev:customers": "vite --config vite.config.customers.ts", // 启动客户应用,同样访问http://localhost:8080/
  "build": "vite build", // 构建后台管理应用
  "build:customers": "vite build --config vite.config.customers.ts", // 构建客户应用到dist/customers
  "preview": "vite preview",
  "preview:customers": "vite preview --config vite.config.customers.ts",
  // 其余lint、type-check等命令保持不变
}

3. 确认路由配置正确性

确保客户应用的router.ts路由基础路径配置为默认根路径:

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

const router = createRouter({
  history: createWebHistory(), // 默认base为'/',匹配根路径访问
  routes
})

export default router

额外提示

  • 若需同时启动两个应用的开发服务器,需在各自的Vite配置中设置不同的port(比如后台用8080,客户应用用8081),避免端口冲突。
  • 公共组件、工具函数等可放在src/shared目录下,两个应用通过@别名引入,保持代码复用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:13:11