Vite详解
阅读原文时间:2021年09月14日阅读:1

vite

目录

Volar

首先推荐Volar,使用vscode开发Vue项目的小伙伴肯定都认识Vetur这个神级插件,有了它可以让我们得开发如鱼得水。 那么Volar可以理解为Vue3版本的Vetur,代码高亮,语法提示,基本上Vetur有的它都有。

Vue 3 Snippets

推荐的第二个插件叫做Vue 3 Snippets,同样的,他也有自己的Vue2版本。它是干什么的呢,可以看一下下面这张图,我只输入了“v3”,它有很多提示,我们就先选择v3computed,选中回车即可。

一种面向现代浏览器的一个更轻、更快的前端构建工具,能够显著提升前端的开发体验。除了Vite外,前端著名的构建工具还有Webpack和Gulp。目前,Vite已经发布了Vite2,Vite全新的插件架构、丝滑的开发体验,可以和Vue3的完美结合。

优势分析

  • Vite 主要对应的场景是开发模式,跳过打包按需加载,因此热更新的速度非常快;

  • 在大型项目上可以有效提高本地开发编译打包的速度,解决 “改一行代码等半天” 问题;

  • 浏览器解析 imports,利用了 type="module" 功能,然后拦截浏览器发出的 ES imports 请求并做相应处理;

  • 闪电般的冷启动速度

  • 即时热模块更换(热更新)

  • 真正的按需编译

    总的来说,Vite希望提供开箱即用的配置,同时它的插件API和JavaScript API带来了高度的可扩展性。不过,相比Vue-cli配置来说,Vite构建的项目还是有很多的配置需要开发者自己进行处理

浏览器支持

  • 开发环境中:Vite需要在支持原生 ES 模块动态导入的浏览器中使用。

  • 生产环境中:默认支持的浏览器需要支持 通过脚本标签来引入原生 ES 模块 。可以通过官方插件 @vitejs/plugin-legacy 支持旧浏览器。

我们可以使用npm或yarn来初始化Vite项目

Node.js的版本需要 >= 12.0.0。

1、创建项目

npm 创建

// 初始化viete项目
npm init vite-app <project-name>
// 进入项目文件夹
cd <project-name>
// 安装依赖
npm install
//启动项目
npm run dev

yarn创建

$ yarn create vite-app <project-name>
$ cd <project-name>
$ yarn
$ yarn dev

创建成功后我看手动加一个vite.config.js配置文件

vite.config.js // 配置文件

2、集成Vue-Router

Vue-Router作为大多数项目必不可少的路由工具,已经被大多数的前端项目所使用,Vue-Router可以让构建单页面应用变得更加的容易。

安装

//npm
npm install vue-router --save

//yarn
yarn add vue-router --save

配置

  • Router 4.x 为我们提供了 createRouter 代替了 Router 3.x 中的 new VueRouter,用于创建路由。

  • Router 4.x 中为我们提供了 createWebHashHistory 与 createWebHistory 方法设置哈希模式与历史模式。

    import { createRouter, createWebHistory } from 'vue-router'
    const routes = [
    {
    path: '/',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    }
    ]
    const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
    })
    export default router

main.js引入

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

3、集成vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

安装

//npm
npm install vuex@next --save
//yarn
yarn add vuex@next --save

配置

import { createStore } from 'vuex'
export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

main.js引入

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(store).use(router).mount('#app')

完成上述操作之后,接下来我们给Vuex编写一个测试代码看Vuex是否有效。修改Home.vue的代码如下。

<template>
  <h1>Home Page</h1>
  <h2>{{count}}</h2>
  <button @click="handleClick">click</button>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
  setup () {
    const store = useStore(); //实例化vuex
    const count = computed(() => store.state.home.count);
    const handleClick = () => {
      store.commit('home/add');
    };
    return {
      handleClick,
      count
    };
  }
})
</script>

4、集成Eslint

ESLint是一个用来识别 ECMAScript语法, 并且按照规则给出报告的代码检测工具,使用它可以避免低级错误和统一代码的风格

安装

npm方式

npm install eslint -D
npm install eslint-plugin-vue -D
npm install @vue/eslint-config-typescript -D
npm install @typescript-eslint/parser -D
npm install @typescript-eslint/eslint-plugin -D
npm install typescript -D
npm install prettier -D
npm install eslint-plugin-prettier -D
npm install @vue/eslint-config-prettier -D

yarn方式

yarn add eslint --dev
yarn add eslint-plugin-vue --dev
yarn add @vue/eslint-config-typescript --dev
yarn add @typescript-eslint/parser --dev
yarn add @typescript-eslint/eslint-plugin --dev
yarn add typescript --dev
yarn add prettier --dev
yarn add eslint-plugin-prettier --dev
yarn add @vue/eslint-config-prettier --dev

安装完成之后,还需要根目录下创建一个.eslintrc文件,如下。

{
  "root": true,
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "extends": [
    "plugin:vue/vue3-recommended",
    "eslint:recommended",
    "@vue/typescript/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 2021
  }
}

package.json文件的scripts中添加如下命令

{
    "lint": "eslint --ext src/**/*.{ts,vue} --no-error-on-unmatched-pattern"
}

问题

如果有很多文件的话,那么校验起来速度将会很慢,此时,我们一般只在git提交的时候才对修改的文件进行eslint校验,那么我们可以这么做。

那就需要使用 lint-staged插件。

//npm
npm install lint-staged -D
//yarn
yarn add lint-staged --dev

package.json修改

{
  "gitHooks": {
    "commit-msg": "node scripts/commitMessage.js",
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{ts,vue}": "eslint --fix"
  },
  "scripts": {
    "test:unit": "jest",
    "test:e2e": "cypress open",
    "test": "yarn test:unit && npx cypress run",
    "lint": "npx prettier -w -u . && eslint --ext .ts,.vue src/** --no-error-on-unmatched-pattern",
    "bea": "npx prettier -w -u ."
  },
}

5、集成element-plus

首先,在项目的根目录下安装element-plus,命令如下:

npm install element-plus --save

引入element-plus

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

6、移动端适配

安装postcss-pxtorem

npm install postcss-pxtorem -D

在根目录下创建postcss.config.js

module.exports = {
 "plugins": {
 "postcss-pxtorem": {
  rootValue: 37.5,
  // Vant 官方根字体大小是 37.5
  propList: ['*'],
  selectorBlackList: ['.norem']
  // 过滤掉.norem-开头的class,不进行rem转换
 }
 }
}

在根目录src中新建util目录下新建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.onresize = function () {
 console.log("我执行了")
 setRem()
}

在mian.js引入

import "./utils/rem"

1、 配置alias起别名

在过去使用vue-cli的时候,我们总是使用@去引入某些文件,由于Vite没有提供类似的配置,所以我们需要手动的对其进行相关配置,才能继续使用@符号去快捷的引入文件。

我们需要修改vite.config.js的配置。

module.exports = {
  alias: {
    // 键必须以斜线开始和结束
    '/@/': path.resolve(__dirname, './src')
  }
}

2、proxy代理配置

server: {
    // hostname: '0.0.0.0',
    host: "localhost",
    port: 3001,
    // // 是否自动在浏览器打开
    // open: true,
    // // 是否开启 https
    // https: false,
    // // 服务端渲染
    // ssr: false,
    proxy: {
      '/api': {
        target: 'http://localhost:3333/',
        changeOrigin: true,
        ws: true,
        rewrite: (pathStr) => pathStr.replace('/api', '')
      },
    },
},

3、按需引入element plus

  1. 安装vite-plugin-style-import

    yarn add vite-plugin-style-import -D

  2. 在项目根目录下的vite.config.js中配置

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import styleImport from 'vite-plugin-style-import';
    export default defineConfig({
    plugins: [vue(),
    styleImport({
    libs: [{
    libraryName: 'element-plus',
    esModule: true,
    resolveStyle: (name) => {
    return element-plus/lib/theme-chalk/${name}.css;
    },
    resolveComponent: (name) => {
    return element-plus/lib/${name};
    },
    }]
    })]
    })

webpack慢的原因

当我们使用如 webpack 的打包工具时,经常会遇到改动一小行代码,webpack 常常需要耗时数秒甚至十几秒进行重新打包。这是因为 webpack 需要将所有模块打包成一个一个或者多个模块。

如下面的代码为例,当我们使用如 webpack 类的打包工具时。最终会将所有的代码打包入一个 bundle.js 文件中

我们常用如 thread-loader , cache-loader ,代码分片等方法进行优化。但随着项目规模的进一步扩大,热更新速度又将变慢,又将开始新一轮的优化。随着项目规模的不断扩大,基于 bunder 构建的项目优化也将达到一定的极限。

vite实现

Vite 的是通过 WebSocket 来实现热更新通信,当代码改动以后,通过 websocket 仅向浏览器推送改动的文件。

因此 Vite 本地热更新的速度不会受项目的大小影响太多,在大型项目中本地开发速度快。

Vite 的客户端热更新代码是在 app.vue 文件编译过程中,将代码注入进去的。

vue-cli优缺点

vue-cli优点

vue-cli缺点

有很多成型项目,可靠

开发服务器速度与依赖数量成反比

完全兼容vue2

可绑定任何类型的依赖关系

插件生态系统完整

vite优缺点

vite优点

vite缺点

开发服务器比webpack快10倍以上

只能对(ES2015+)以上现代浏览器支持

将 code-splitting 作为优先事项

与 CommonJS 模块不完全兼容

-

处于测试阶段,仅支持 Vue 3

-

最小的脚手架不包括 Vuex、路由器等

-

不同的开发服务器与构建工具