Vite 构建多页面应用以 HTML 文件为入口,需在 vite.config.ts 中通过 build.rollupOptions.input 明确配置每个页面的 HTML 路径,如 home: resolve(__dirname, 'src/pages/home/index.html'),构建后生成对应独立资源;目录结构须匹配访问路径,如 /admin/ 对应 admin/index.html;支持通过命令行参数(如 --app=admin)动态指定构建目标。

Vite 构建多页面应用(MPA)时,打包入口不是靠“写多个 JS 入口文件”来定义的,而是以 每个 HTML 文件为独立构建上下文。核心原则是:HTML 即入口 —— 你有多少个要上线的页面,就得有多少个独立的 index.html(或命名如 admin.html、login.html),且它们必须在构建时被明确声明为 input。
入口必须是 HTML 文件路径
Vite 的构建系统基于 Rollup,而 Rollup 的 input 选项决定哪些资源参与构建。对多页应用来说,这个 input 应该指向 HTML 文件,而不是 JS 文件。因为:
- HTML 文件自带模板结构、标题、meta 标签和挂载点;
- Vite 开发服务器会根据 HTML 路径自动映射路由(例如访问
/admin/就加载admin/index.html); - 只设 JS 为 input 会导致缺失 HTML 输出,无法直接部署访问。
配置 build.rollupOptions.input 映射页面
在 vite.config.ts 或 vite.config.js 中,通过 build.rollupOptions.input 指定每个页面的 HTML 入口路径。推荐使用 path.resolve 确保路径准确:
import { defineConfig } from 'vite';
import { resolve } from 'path';
export default defineConfig({
build: {
rollupOptions: {
input: {
home: resolve(__dirname, 'src/pages/home/index.html'),
about: resolve(__dirname, 'src/pages/about/index.html'),
contact: resolve(__dirname, 'src/pages/contact/index.html')
}
}
}
});
构建后,Vite 会为每个 key(如 home)生成独立的 HTML、JS 和 CSS 文件,并保持对应关系。
立即学习“Java免费学习笔记(深入)”;
目录结构需匹配运行时路径
浏览器访问路径与文件系统路径强相关。例如:
- 访问
http://localhost:5173/→ 加载项目根目录下的index.html; - 访问
http://localhost:5173/admin/→ 自动查找admin/index.html; - 访问
http://localhost:5173/login/→ 查找login/index.html。
因此,建议将各页面放在独立子目录中,每个目录下包含:index.html(含正确 <script type="module"> 引用)、main.ts(Vue 实例挂载)、App.vue(页面根组件)。
支持动态构建单个页面(可选进阶)
若项目含多个页面但希望按需构建(如 CI/CD 中只发布 admin),可通过命令行参数动态读取构建目标:
- 运行:
vite build --app=admin - 在配置中解析:
process.argv.find(arg => arg.startsWith('--app='))?.split('=')[1] - 据此设置:
root: `./src/apps/${app}`和input: resolve(__dirname, `src/apps/${app}/index.html`) - 同时指定
build.outDir: `dist/${app}`避免产物混杂。


















