【实战技巧】Vue3+Vite工程常用工具的接入方法

3,774 阅读6分钟

Vue3 正式版已经发布一段时间了,和 Vue3 更配的工具 Vite 也已经投入使用了,本文整理了如何将一些常用的工具整合到项目中。

包括 vue-router , vuex , typescript , sass , axios , elementUI , vant。以及配置 环境变量,假数据 mock 等。

新建项目目录

输入命令,然后会让你填写工程名称,选择你要使用的技术栈,按照提示操作即可!

//yarn
yarn create @vitejs/app
//npm
npm init @vitejs/app

配置文件

Vite 的配置文件就是 根目录 下的 vite.config.js

vitevue 需要以插件的形式引入,但是脚手架已经给写好了,了解一下就行。

如果使用 TS ,则需要先安装类型声明文件。

npm install --save-dev @types/node

导入了 defineConfig 插件以后,书写配置文件就可以有代码提示了。

vite 中,定义别名不再需要添加 '/'

//vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  //定义别名
  alias: {
    "@": path.resolve(__dirname, "src"),
    coms: path.resolve(__dirname, "src/components"),
  },
  css: {},
  plugins: [
    vue(),
  ],
});

整合axios

安装依赖

//yarn
yarn add  axios  -S    
//npm
npm i axios  -S 

src目录 下创建 utils 文件夹,并在 utils目录 下创建 request.js

大家也可以根据自身需求对 axios 进行二次封装。

//request.ts
import axios from 'axios';
const baseURL = '';
const service = axios.create({
  baseURL,
  timeout: 5000, // request timeout
});
// 发起请求之前的拦截器
service.interceptors.request.use(
  (config) => {
    // 如果有token 就携带tokon
    const token = window.localStorage.getItem('accessToken');
    if (token) {
      config.headers.common.Authorization = token;
    }
    return config;
  },
  (error) => Promise.reject(error)
);
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (response.status !== 200) {
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      return res;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);
export default service;

使用

import request from "../utils/request";

request({url: "/profile ",method: "get"})
.then((res)=>{
  console.log(res)
})

整合mock数据

通过 yarnnpm 进行安装

//yarn
yarn add mockjs -S   
yarn add vite-plugin-mock -D
yarn add cross-env -D
//npm
npm i mockjs -S   
npm i vite-plugin-mock -D
npm i cross-env -D

安装完之后需要配置 vite.config.js ,如果使用 js发开,则需要配置 supportTsfalse。其它默认即可。

如果是 ts ,则不需要配置 supportTs

//导入
import { viteMockServe } from "vite-plugin-mock";
//plugins
 plugins: [vue(), viteMockServe({ supportTs: false })],

设置环境变量,这里要设置为开发环境,下面会讲怎么整合环境变量。

//package.json	  
  "scripts": {
    "dev": "cross-env NODE_ENV=development vite",
  },

然后我们建一个测试接口进行测试

根目录 下新建 mock 文件夹, mock 文件夹下新建 users.js

//user.js
export default [
  {
    url: "/api/getUsers",
    method: "get",
    response: () => {
      return {
        code: 0,
        message: "ok",
        data: ["tom", "jerry"],
      };
    },
  },
];

在组件中发起请求

//app.vue
//此处是封装好的axios请求
request({ url: '/api/getUsers', method: 'get' }).then((res) => {
  console.log(res);
});

整合环境变量

根目录 下创建 .env.development.env.production 文件。

// .env.development
VITE_APP_ENV = 'development'
// .env.production
VITE_APP_ENV = 'production'

修改 package.json,对环境变量进行配置。

//package.json	  
"scripts": {
  "dev": "cross-env NODE_ENV=development vite",
  "build:dev": "vite build --mode development",
  "build:pro": "vite build --mode production"
},

整合vue-router

通过 yarnnpm 进行安装,由于 vue-router4 还没有转成正式版,所以需要加 next

//yarn
yarn add  vue-router@next -S    
//npm
npm i  vue-router@next -S   

src目录 下新建 router 文件夹

//router/index.js
import { createRouter, createWebHashHistory } from "vue-router";
// hash模式  createWebHashHistory
// history模式  createWebHistory

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      component: () => import("../views/Home.vue"),
    },
  ],
});
    
export default router;

在入口文件中引入

//main.js
import router from "./router";
createApp(App).use(router).mount("#app");

在组件中使用,vue-router 的使用和新特性不属于本文的内容。

//App.vue
//在根节点上添加router-view
<template>
  <router-view></router-view>
</template>

整合vuex

通过 yarnnpm 进行安装,由于 vuex 还没有转成正式版,所以需要加 next

//yarn
yarn add vuex@next -S    
//npm
npm i vuex@next  -S   

src目录 下新建 store 文件夹

//store/index.js
import { createStore } from "vuex";
export default createStore({
  state: {
    couter: 109,
  },
});

在入口文件中引入。

//main.js
import store from "./store";
createApp(App).use(router).use(store).mount("#app");

整合SASS

通过 yarnnpm 进行安装。

//yarn
yarn add sass -D  
//npm
npm i sass -D  

src目录 下新建 styles 文件夹, index.scss 来存放全局样式

//styles/index.scss
a {
  color: red;
}

可以分成多个文件,在 index.scss 中导入即可

//styles/index.scss
@import './element-ui.scss' //组件库的样式覆盖
@import './variables.scss' //全局变量

整合typescript

只需要在创建项目的时候选择 vue-ts 选项,然后脚手架就会生成 shims-vue.d.ts 文件来支持 ts

然后只需要在 script 标签中添加 lang='ts' 即可

<script lang="ts">
    //do something
</script>

整合element组件库

首先安装

//yarn
yarn add  element-plus  -S    
//npm
npm i element-plus  -S 

src目录 下新建 plugins 文件夹, plugins目录下 新建 elementPlus.js 文件

整体引入

//elementPlus.js

import ElementPlus from "element-plus";
import "element-plus/lib/theme-chalk/index.css";

export default function (app) {
  //整体引入
  app.use(ElementPlus);
}

按需引入

import { ElButton } from "element-plus";
import { ElInput } from "element-plus";

import "element-plus/lib/theme-chalk/index.css";

export default function (app) {
  //按需引入
  app.use(ElButton);
  app.use(ElInput);
}

修改 main.js

import ElementPlus from "plugins/elementPlus";

createApp(App).use(ElementPlus).mount("#app");

移动端适配

安装依赖

//yarn
yarn add postcss-pxtorem -D
yarn add autoprefixer -D
//npm
npm install postcss-pxtorem -D
npm install autoprefixer -D

根目录 下创建 postcss.config.js

module.exports = {
  "plugins": {
    // 兼容浏览器,添加前缀
    autoprefixer: {
      overrideBrowserslist: [
        "Android 4.1",
        "iOS 7.1",
        "Chrome > 31",
        "ff > 31",
        "ie >= 8",
        "last 10 versions", // 所有主流浏览器最近10版本用
      ],
      grid: true,
    },
    "postcss-pxtorem": {
      // Vant 官方根字体大小是 37.5
      rootValue: 37.5, 
      //是一个存储哪些将被转换的属性列表,这里设置为['*']全部,假设需要仅对边框进行设置,可以写['*', '!border*']
      propList: ['*'],
      // 过滤掉.norem-开头的class,不进行rem转换
      selectorBlackList: ['.norem'],
      unitPrecision: 5, //保留rem小数点多少位
      mediaQuery: false, // 媒体查询( @media screen 之类的)中不生效
      minPixelValue: 12, // px小于12的不会被转换
    }
  }
}

src目录下 中新建 util 文件夹, util目录 下新建 rem.js 等比适配文件

// rem.js
// rem等比适配配置文件
// 基准大小
const baseSize = 37.5 
// 注意此值要与 postcss.config.js 文件中的 rootValue保持一致
// 设置 rem 函数
function setRem () {
  // 当前页面宽度相对于 375宽的缩放比例,可根据自己需要修改,一般设计稿都是宽750(图方便可以拿到设计图后改过来)。
  const scale = document.documentElement.clientWidth / 375
  // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.addEventListener('resize', () => {
  console.log('我执行了');
  setRem();
});

mian.ts 中引入

import "./utils/rem"

整合vant组件库

安装依赖

yarn add vant@next -S
npm i vant@next -S

注意: vite 版本不需要配置组件的按需加载,因为 Vant 3.0 内部所有模块都是基于 ESM 编写的,天然具备按需引入的能力,但是样式必须全部引入。

plugins文件夹 下新建 vant.js

import Vant from 'vant';
import 'vant/lib/index.css';

export default function (app) {
  app.use(Vant);
}

修改 main.js

//main.js
import Vant from 'plugins/vant';
createApp(App).use(Vant).mount('#app');

整合代码规范插件eslint,prettier

安装依赖

yarn add babel-eslint -D
yarn add @vue/eslint-config-prettier -D
yarn add eslint -D
yarn add eslint-plugin-prettier -D
yarn add eslint-plugin-vue -D
yarn add prettier -D

根目录 下新建 .eslintrc.js

//.eslintrc.js
module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: ['plugin:vue/vue3-essential', 'eslint:recommended'],
  parserOptions: {
    parser: 'babel-eslint',
  },
  rules: {
    //在此处写规则
    'no-unused-vars': 0, // 定义未使用的变量
  },
};

根目录 下新建 .prettierrc.json

//.prettierrc.json
{
  //此处填写规则
  "singleQuote": true,//单引号
  "seme": true,//分号
  "tabWidth": 2,//缩进
  "TrailingCooma": "all",//尾部元素有逗号
  "bracketSpacing": true,//对象中的空格
}

再结合 vscode 的保存自动格式化

 //settings.json
"editor.formatOnSave": true,//保存时格式化
"files.autoSave": "onFocusChange", //失去焦点时保存
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true
},
"eslint.validate": [
  "javascript",
  "javascriptreact",
  "typescript"
],  

配置GZIP压缩

安装依赖

yarn add vite-plugin-compression -D

修改 vite.config.js

//vite.config.js

import viteCompression from 'vite-plugin-compression'
plugins:[
  ...
  viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz'
  })
]

部署发布

执行对应命令即可

"dev": "cross-env NODE_ENV=development vite",
"serve": "vite preview",
"build:dev": "vite build --mode development",
"build:pro": "vite build --mode production"

新建本地服务器

进入到目标文件夹

npm init -y

安装 vite

yarn add vite -D

修改 package.json

  "scripts": {
    "dev": "vite"
  },

然后启动即可

npm run dev

根目录下新建 index.html

访问 http://localhost:3000/index.html 就可以看见页面了

单独使用TS搭建本地服务