vite 配置多页面应用需将每个 html 设为独立入口,统一放于 src/pages/ 下并用绝对路径引用脚本;在 vite.config.js 中通过 build.rollupoptions.input 指定各页面 index.html 路径,支持手动配置或 fs 自动扫描。

在 Vite 中配置多页面应用(MPA),核心是让每个 HTML 页面成为独立构建入口,并确保开发和生产环境都能正确加载各自资源。不需要改写底层逻辑,关键在目录结构、HTML 引用路径和 vite.config.js 的 build.rollupOptions.input 配置。
明确页面入口与目录结构
每个页面应有自己完整的 HTML 文件,建议统一放在 src/pages/ 下,按页面命名建子目录:
src/pages/home/index.htmlsrc/pages/about/index.htmlsrc/pages/contact/index.html
每个 index.html 中的脚本引用必须使用绝对路径(以 / 开头),例如:
这样 Vite 才能正确定位模块并做 HMR 和构建处理。避免相对路径或未加前缀的路径,否则开发时可能报 404。
配置 vite.config.js 指定多个入口
在 vite.config.js 中通过 build.rollupOptions.input 显式声明每个页面的 HTML 入口:
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 会为每个入口生成独立的 JS/CSS 资源,并保留对应 HTML 文件,输出结构类似:
dist/home/
index.html
about/
index.html
contact/
index.html
assets/...(共用或按需拆分的资源)
可选:自动化扫描 HTML 入口
当页面数量变多时,手动维护 input 容易出错。可用 Node.js 的 fs 模块自动收集:
const path = require('path')
const getPages = () => {
const pagesDir = path.resolve(__dirname, 'src/pages')
const dirs = fs.readdirSync(pagesDir, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => d.name)
return Object.fromEntries(
dirs.map(dir => [
dir,
path.resolve(__dirname, `src/pages/${dir}/index.html`)
])
)
然后在配置中直接使用:input: getPages()。这种方式适合中大型 MPA 项目,后续增删页面只需增减目录,无需改配置。
注意开发服务器访问方式
Vite 开发服务器默认只服务 / 路径。要访问多页面,需手动输入完整路径,例如:
http://localhost:5173/home/http://localhost:5173/about/
如果希望根路径重定向到某个页面(如 home),可在 public/ 放一个 index.html 做跳转,或借助插件如 vite-plugin-rewrite 实现简单路由代理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











