本博客会详细介绍打包脚手架初始项目的完整流程,无任何坑!
1.脚手架克隆项目
运行下列命令:
vue create [your project name]
接着根据自己的需求选择配置即可
2.打包关键与问题介绍
初始化项目后,可以看到默认给出了三个脚本:
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" },
此时好像直接运行如下代码之一就能打包:
npm run build yarn run build
打包之后的项目结构如下:
-dist --css --js --favicon.ico --index.html
直接访问index.html你会发现一片空白!打包失败!
3.打包问题解决
3.1 解决publicPath中的./相对路径
找到vue.config.js文件,初始内容如下:
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true })
此时需要我们添加一行publicPath,代码如下:
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, publicPath:"./" })
根本原因:引用项目资源不是从/根目录开始的,而是从./相对目录开始。
3.2 修改路由为Hash模式
如果使用了router(若没使用就可以跳过这步骤),找到router文件夹下的index.js文件,将路由的History模式修改为Hash模式:
初始内容如下:
const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes })
修改内容如下:
const router = createRouter({ history: createWebHashHistory(process.env.BASE_URL), routes })
大功告成!
4. 打包项目
直接运行如下代码之一打包:
npm run build yarn run build
运行完之后访问index.html,打包成功!
如果此博客对您有帮助,请留下您宝贵的一个赞!