Vue3 + Vite多页面应用配置:实现不同路由独立HTML入口
Vue3 + Vite 实现多页面入口配置
1. 调整项目目录结构
为避免文件重名冲突,把不同页面的文件归类到单独目录,建议结构如下:
├── index.html # 主页面入口HTML ├── src/ │ ├── main.js # 主页面入口JS │ ├── product1/ │ │ ├── index.html # 对应路由/product1的入口HTML │ │ └── main.js # /product1页面的入口JS │ └── product2/ │ ├── index.html # 对应路由/product2的入口HTML │ └── main.js # /product2页面的入口JS
2. 修改 Vite 配置文件
在项目根目录的 vite.config.js 中,配置多页面入口路径,并处理开发环境的路由映射:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], build: { rollupOptions: { // 定义每个页面的入口文件 input: { main: './index.html', product1: './src/product1/index.html', product2: './src/product2/index.html' } } }, server: { // 开发时,访问/product1或/product2时映射到对应HTML文件 proxy: { '/product1': { target: 'http://localhost:5173', rewrite: (path) => path.replace(/^\/product1/, '/src/product1/index.html') }, '/product2': { target: 'http://localhost:5173', rewrite: (path) => path.replace(/^\/product2/, '/src/product2/index.html') } } } })
3. 编写各页面入口代码
每个页面的 main.js 需单独初始化Vue实例,以 src/product1/main.js 为例:
import { createApp } from 'vue' // 引入product1专属的组件文件 import App from './App.vue' createApp(App).mount('#app')
对应的 src/product1/index.html 要添加挂载节点:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Product1 页面</title> </head> <body> <div id="app"></div> <script type="module" src="./main.js"></script> </body> </html>
product2的代码逻辑与product1一致,替换对应文件即可。
4. 验证效果
- 开发阶段:运行
npm run dev后,访问http://localhost:5173是主页面,访问http://localhost:5173/product1可打开product1的独立页面 - 构建阶段:执行
npm run build后,dist目录会生成各页面的独立文件,包括index.html、product1.html、product2.html及对应静态资源包
若无需完全隔离的页面,也可结合Vue Router在主应用内做路由跳转,但多入口方式更适合资源完全隔离的场景。
内容的提问来源于stack exchange,提问作者rendom
相关产品推荐
相关产品推荐

