解决Vue项目打包后dist中的index.html用浏览器无法直接打开的问题
将绝对路径改为相对路径
可以选择手动将index.html中所有引用资源的地方全部改成相对路径,如:<link href=./css/chunk-00d5eabc.f78fa75d.css rel=prefetch>或<link href=css/chunk-00d5eabc.f78fa75d.css rel=prefetch>。
当然,更优雅的做法是修改项目 vue.config.js 文件中的 publicPath:
// vue.config.js
module.exports = {
// ...
publicPath: './'
// ...
};
此时再运行npm run build打包后,打开 dist/index.html 发现所有资源的引用形式已经变为相对路径:<link href=css/chunk-00d5eabc.f78fa75d.css rel=prefetch>,此时可以双击 index.html 在浏览器中正常访问了!
但是如果页面有路由跳转的话,会发现跳转失败,
这时需要修改router中的路由模式为hash:
在 router 的 index.js 中修改:从 vue-router 中引入 createWebHashHistory,将 createWebHistory(process.env.BASE_URL) 改为 createWebHashHistory(process.env.BASE_URL)
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = createRouter({
// history: createWebHistory(process.env.BASE_URL), // history 模式
history: createWebHashHistory(process.env.BASE_URL), // hash 模式
routes
})

浙公网安备 33010602011771号