项目场景:
关于如何将vue项目打包
通过将npm run build
将vue项目打包
问题描述
vue打包过程问题
vue采用单页面文件形式,打包之后index.html是vue项目打包之后的页面
问题1:运行index.html内容为空:
**控制台报错信息**
原因:由于项目打包默认路劲从‘ / ’开始,要改为‘ ./ ’
修改文件vue.config.js中添加以下代码:
publicPath: './'
重新打包打开index.html文件,页面访问成功
问题2:index.html页面正常访问,但路由跳转页面不能正常访问或者刷新后页面找不到文件:
问题分析:由于项目打包成功且index.html可以正常访问,问题不是项目打包的原因,而出现路由跳转的时候查找不到路径,通过官方文档了解到,是因为vue中router采用了history模式,配置文件:router/index.js文件下
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
...
路由配置信息
...
const router = createRouter({
history: createWebHistory(), //原代码
routes
})
报错信息如下:
此时我们需要将histroy模式改为hash模式,将路径地址转换为hash模式,路由跳转页面便可以正常访问
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
...
路由配置信息
...
const router = createRouter({
history: createWebHashHistory(), //原代码
routes
})
histroy与hash模式的区别
histroy模式下路径地址:file:///D:/demo/test01/dist/index.html
hash模式下路径地址:file:///D:/demo/test01/dist/index.html#/
总结:
vue项目打包过程总结:
- 将vue.config.js项目中打包路径修改为根路径:‘./’
- 将router/index.js路由文件histroy修改为hash模式
- 打包文件
打包之后项目的运行:
1.安装http-server,使用node命令全局安装
cnpm install http-server -g
- 进入打包文件(默认为:dist)
cd dist
- 运行命令:
http-server