如何按指定目录结构使用Vite创建多页面应用并解决访问异常问题
问题原因
你当前仅配置了生产构建阶段的Rollup入口,没有适配开发服务器的路径映射规则,且Vite默认会优先读取项目根目录下的index.html作为入口,你将所有页面存放在pages目录下后,原访问路径和实际文件路径不匹配,因此无法正常加载页面。
解决步骤
1. 调整vite.config.js配置
补充开发服务的权限配置,保留原生产构建的入口配置即可,完整配置如下:
// vite.config.js const { resolve } = require('path') module.exports = { // 开发服务配置 server: { fs: { // 允许开发服务访问pages目录下的资源 allow: ['.'] } }, build: { rollupOptions: { input: { main: resolve(__dirname, 'pages/main/index.html'), admin: resolve(__dirname, 'pages/admin/index.html') } } } }
2. 确认页面内资源引用路径
检查pages/main/index.html和pages/admin/index.html中对main.js的引用路径是否为相对路径,示例如下:
<!-- pages/main/index.html 内的script引入 --> <script type="module" src="./main.js"></script>
3. 访问路径说明
配置完成后重启开发服务:
- 主页面访问地址:
http://localhost:5173/pages/main/index.html(Vite 3+默认端口为5173,2.x版本为3000) - 管理页访问地址:
http://localhost:5173/pages/admin/index.html
如果你想要省略路径中的pages前缀,可额外添加路由重写配置:
// 在server配置中新增rewrites规则 server: { fs: { allow: ['.'] }, rewrites: [ { from: /^\/admin/, to: '/pages/admin/index.html' }, { from: /^\/$/, to: '/pages/main/index.html' } ] }
配置后可直接通过http://localhost:5173访问主页面,http://localhost:5173/admin访问管理页。
内容的提问来源于stack exchange,提问作者radiorz
相关产品推荐
相关产品推荐

