手把手教你搭建vue3+vite+vant移动端项目
随着vue3越来越成熟,加之vite的出现。所以笔者最近尝试了一下用vite+vue3搭建一个移动端项目,所以记录一下搭建的过程。有需要的小伙伴可以作为参考来搭建,可以少走很多弯路。
初始化项目
兼容性:Vite 需要 Node.js 版本 >= 12.0.0。
vite提供不同工具的初始化
1、通过npm初始化
npm init vite@latest 复制代码
2、通过Yarn
yarn create vite 复制代码
3、通过PNPM
pnpm dlx create-vite 复制代码
以npm为例:
1、项目名称
2、选择框架
3、是否需要引入ts
4、完成
通过指定具体的模板
通过附加的命令行选项直接指定项目名称和你想要使用的模板。例如要构建一个 Vite + Vue 项目,可运行一下命令:
# npm 6.x npm init vite@latest my-vue-app --template vue # npm 7+, 需要额外的双横线: npm init vite@latest my-vue-app -- --template vue # yarn yarn create vite my-vue-app --template vue 复制代码
支持的模板预设包括:
vanilla
vanilla-ts
vue
vue-ts
react
react-ts
preact
preact-ts
lit-element
lit-element-ts
svelte
svelte-ts
查看 create-vite 以获取每个模板的更多细节。
引入eslint提高代码质量
安装eslint及相关插件
npm install eslint eslint-plugin-vue babel-eslint -D 复制代码
根目录下新建.eslintrc.js
文件,定义eslint规则
// .eslintrc.js module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true, node: true, es6: true }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended' ], // add your custom rules here rules: { // "off" or 0 - 关闭规则 // "warn" or 1 - 将规则视为一个警告 // "error" or 2 - 将规则视为一个错误 // allow async-await 'generator-star-spacing': 'off', // 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', // allow debugger during development // 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', /** * 最佳实践 */ eqeqeq: 2, // 强制使用 === 和 !== 'default-case': 1, // 要求 switch 语句中有 default 分支 'no-else-return': 1, // 禁止 if 语句中 return 语句之后有 else 块 'no-empty-function': 1, // 禁止出现空函数 'no-multi-spaces': 1, // 禁止使用多个空格 radix: 1, // 强制在parseInt()使用基数参数 /** * 变量声明 */ 'init-declarations': ['error', 'always'], // 声明变量必须赋值 /** * ECMAScript6 */ 'arrow-spacing': ['error', { before: true, after: true }], // 强制箭头函数的箭头前后使用空格 'no-var': 2, // 禁止使用 var 声明变量 'object-shorthand': 2, // 要求使用对象方法名和属性名简写 'prefer-arrow-callback': 2, // 要求回调函数使用箭头函数 'prefer-const': 2, // 使用 const 声明那些声明后不再被修改的变量 'prefer-rest-params': 2, // 要求使用剩余参数而不是 arguments /** * 风格指南 */ 'space-before-function-paren': 0, // 函数名称或function关键字与开始参数之间允许有空格 'array-bracket-spacing': 0, // 数组方括号内必须空格 'comma-dangle': 2, // 禁止末尾逗号 'eol-last': 2, // 要求文件末尾存在空行 // 对象冒号前禁止空格,冒号后必须空格 'key-spacing': ['error', { beforeColon: false, afterColon: true }], // 关键字(if、else等)前后必须有空格 'keyword-spacing': ['error', { before: true, after: true }], // 禁止出现多行空行 'no-multiple-empty-lines': ['error', { max: 1 }], semi: ['error', 'never'], // 禁止末尾分号 quotes: ['error', 'single'], // 强制使用单引号 'space-infix-ops': 2, // 操作符周围必须有空格 'spaced-comment': ['error', 'always'], // 注释后面必须跟随至少一个空白 'object-curly-spacing': 0, 'no-unused-expressions': 0 } } 复制代码
根目录下新建.eslintignore
文件,需要忽略eslint检查的目录或文件
/dist/ /node_modules/ 复制代码
在package.json
中的scripts
配置中增加以下脚本命令
"lint": "eslint --ext .vue,.js ./", "lint:fix": "eslint --fix --ext .vue,.js ./" 复制代码
引入prettier统一代码风格
安装prettier及相关eslint插件
npm install prettier eslint-config-prettier eslint-plugin-prettier -D 复制代码
根目录下新建.prettierrc.js
文件,定义perttier规则
// .preitterrc.js module.exports = { // 一行的字符数,如果超过会进行换行,默认为80 printWidth: 80, // 一个tab代表几个空格数,默认为80 tabWidth: 2, // 是否使用tab进行缩进,默认为false,表示用空格进行缩减 useTabs: false, // 字符串是否使用单引号,默认为false,使用双引号 singleQuote: true, // 行位是否使用分号,默认为true semi: false, // 是否使用尾逗号,有三个可选值"<none|es5|all>" trailingComma: "none", // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar } bracketSpacing: true, // 代码的解析引擎,默认为babylon,与babel相同 // "parser": "babylon", // 开启 eslint 支持 eslintIntegration: true } 复制代码
修改eslint(.eslintrc.js)配置
1、在extends
配置值增加plugin:prettier/recommended
2、在rules
配置值增加'prettier/prettier': 'error'
修改后的.eslintrc.js文件如下:
// .eslintrc.js module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true, node: true, es6: true }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended', 'plugin:prettier/recommended' ], // add your custom rules here rules: { // "off" or 0 - 关闭规则 // "warn" or 1 - 将规则视为一个警告 // "error" or 2 - 将规则视为一个错误 'prettier/prettier': 'error', // allow async-await 'generator-star-spacing': 'off', // 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', // allow debugger during development // 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', /** * 最佳实践 */ eqeqeq: 2, // 强制使用 === 和 !== 'default-case': 1, // 要求 switch 语句中有 default 分支 'no-else-return': 1, // 禁止 if 语句中 return 语句之后有 else 块 'no-empty-function': 1, // 禁止出现空函数 'no-multi-spaces': 1, // 禁止使用多个空格 radix: 1, // 强制在parseInt()使用基数参数 /** * 变量声明 */ 'init-declarations': ['error', 'always'], // 声明变量必须赋值 /** * ECMAScript6 */ 'arrow-spacing': ['error', { before: true, after: true }], // 强制箭头函数的箭头前后使用空格 'no-var': 2, // 禁止使用 var 声明变量 'object-shorthand': 2, // 要求使用对象方法名和属性名简写 'prefer-arrow-callback': 2, // 要求回调函数使用箭头函数 'prefer-const': 2, // 使用 const 声明那些声明后不再被修改的变量 'prefer-rest-params': 2, // 要求使用剩余参数而不是 arguments /** * 风格指南 */ 'space-before-function-paren': 0, // 函数名称或function关键字与开始参数之间允许有空格 'array-bracket-spacing': 0, // 数组方括号内必须空格 'comma-dangle': 2, // 禁止末尾逗号 'eol-last': 2, // 要求文件末尾存在空行 // 对象冒号前禁止空格,冒号后必须空格 'key-spacing': ['error', { beforeColon: false, afterColon: true }], // 关键字(if、else等)前后必须有空格 'keyword-spacing': ['error', { before: true, after: true }], // 禁止出现多行空行 'no-multiple-empty-lines': ['error', { max: 1 }], semi: ['error', 'never'], // 禁止末尾分号 quotes: ['error', 'single'], // 强制使用单引号 'space-infix-ops': 2, // 操作符周围必须有空格 'spaced-comment': ['error', 'always'], // 注释后面必须跟随至少一个空白 'object-curly-spacing': 0, 'no-unused-expressions': 0 } } 复制代码
增加vscode配置文件settings.json
实现保存自动格式化
注意点:可能你本地装的很多插件会导致各种和eslint冲突的问题,需要根据情况把这些冲突问题解决。
在根目录下新建.vscode
目录,在该目录中新建settings.json
文件
{ //保存时eslint自动修复错误 新版本改为下面那个配置 // "eslint.autoFixOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, //保存自动格式化 "editor.formatOnSave": true } 复制代码
增加git hook来在提交前进行代码eslint检查
采用husky管理git hook,主要添加以下钩子:
添加
pre-commit
钩子执行eslint检查添加
commit-msg
钩子执行提交代码信息检验
安装husky
npm install husky -D 复制代码
在package.json
中的scripts
配置中增加以下脚本命令
"prepare": "husky install" 复制代码
执行husky install
命令,会自动新增.husky
目录
添加pre-commit
钩子,在.husky
目录下新建pre-commit
文件
往文件写入
#!/bin/sh . "$(dirname "$0")/_/husky.sh" npm run lint:fix 复制代码
添加commit-msg
钩子,在.husky
目录下新建commit-msg
文件
#!/bin/sh . "$(dirname "$0")/_/husky.sh" npx --no-install commitlint --edit $1 复制代码
安装commitlint
校验提交信息格式
npm install @commitlint/cli @commitlint/config-conventional -D 复制代码
根目录下新建commitlint.config.js
文件,定义提交信息格式
/** * feature:新功能 * update:更新某功能 * fixbug:修补某功能的bug * refactor:重构某个功能 * optimize: 优化构建工具或运行时性能 * style:仅样式改动 * docs:仅文档新增/改动 * chore:构建过程或辅助工具的变动 */ module.exports = { extends: [ // 直接继承官网规则 '@commitlint/config-conventional' ] } 复制代码
引入vue-router
安装vue-router
npm install vue-router -S 复制代码
新建router
目录,新建index.js
文件
// index.js import { createRouter, createWebHashHistory } from 'vue-router' import App from '@/App.vue' // 路由规则 const routes = [ { path: '/', component: App, children: [ { path: '', redirect: '/home' }, { path: '/home', name: 'home', component: () => import('@/views/Home.vue') }, { path: '/login', name: 'login', component: () => import('@/views/Login.vue') }, { // vue-router@4的变化,舍弃*通配符 // 官方文档:https://next.router.vuejs.org/zh/guide/migration/index.html#%E5%88%A0%E9%99%A4%E4%BA%86-%EF%BC%88%E6%98%9F%E6%A0%87%E6%88%96%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%89%E8%B7%AF%E7%94%B1 path: '/:pathMatch(.*)*', name: '404', component: () => import('@/views/404.vue') } ] } ] const router = createRouter({ // vueRouter@3版本的mode改成了history,hash模式配置createWebHashHistory,history模式配置createWebHistory history: createWebHashHistory(), routes }) export default router 复制代码
在main.js
中引入router
import router from '@/router' const app = createApp(App) // 路由 app.use(router) 复制代码
引入axios
安装axios
npm install axios -S 复制代码
在utils/http
目录新建index.js
import axios from 'axios' const service = axios.create({ // baseURL: '', timeout: 30 * 1000, // 请求是否携带cookie withCredentials: true }) // 请求拦截器 // service.interceptors.request.use(config => { // }, err => { // }) // 响应拦截器 // service.interceptors.response.use(res => { // }, err => { // }) export default service 复制代码
引入vuex
安装vuex
npm install vuex -S 复制代码
在store
目录新建index.js
import { createStore } from 'vuex' const store = createStore({ state() { return { token: '' } } }) export default store 复制代码
在main.js
中引入vuex
import store from '@/store' const app = createApp(App) // veux app.use(store) 复制代码
引入vant-ui
安装vant
npm i vant@next -S 复制代码
安装vite-plugin-style-import
实现按需加载
npm i vite-plugin-style-import -D 复制代码
在vite.config.js
的plugins
配置中加入以下配置
styleImport({ libs: [ { libraryName: 'vant', esModule: true, resolveStyle: name => `vant/es/${name}/style` } ] }) 复制代码
引入vant rem适配方案
具体可查看官方文档中的rem适配方案
安装amfe-flexible动态计算html的font-szie
npm i amfe-flexible -S 复制代码
安装postcss-pxtorem
npm i postcss-pxtorem -D 复制代码
在vite.config.js
中加入以下配置
// Vite自身已经集成PostCSS,无需再次安装。另外也无需单独创建PostCSS配置文件,已集成到vite.config.js的css选项中 css: { postcss: { plugins: [ postCssPxToRem({ rootValue: 37.5, propList: ['*'], }) ] } }, 复制代码
引入less
安装less和less-laoder
npm i less less-laoder -D
作者:yusongH
链接:https://juejin.cn/post/7012946831877341191