Vite詳解

vite

一、推薦兩個插件插件

Volar

首先推薦Volar,使用vscode開發Vue項目的小夥伴肯定都認識Vetur這個神級插件,有了它可以讓我們得開發如魚得水。 那麼Volar可以理解為Vue3版本的Vetur,代碼高亮,語法提示,基本上Vetur有的它都有。

Vue 3 Snippets

推薦的第二個插件叫做Vue 3 Snippets,同樣的,他也有自己的Vue2版本。它是幹什麼的呢,可以看一下下面這張圖,我只輸入了「v3」,它有很多提示,我們就先選擇v3computed,選中回車即可。

二、vite簡介

一種面向現代瀏覽器的一個更輕、更快的前端構建工具,能夠顯著提升前端的開發體驗。除了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 支持舊瀏覽器。

三、vite搭建vue3.x項目

我們可以使用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"

四、vite.config.js的配置

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: '//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
  1. 在項目根目錄下的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 & Vite 原理對比

webpack慢的原因

當我們使用如 webpack 的打包工具時,經常會遇到改動一小行代碼,webpack 常常需要耗時數秒甚至十幾秒進行重新打包。這是因為 webpack 需要將所有模塊打包成一個一個或者多個模塊。
如下面的代碼為例,當我們使用如 webpack 類的打包工具時。最終會將所有的代碼打包入一個 bundle.js 文件中
我們常用如 thread-loader , cache-loader ,代碼分片等方法進行優化。但隨着項目規模的進一步擴大,熱更新速度又將變慢,又將開始新一輪的優化。隨着項目規模的不斷擴大,基於 bunder 構建的項目優化也將達到一定的極限。

vite實現

Vite 的是通過 WebSocket 來實現熱更新通信,當代碼改動以後,通過 websocket 僅向瀏覽器推送改動的文件。
因此 Vite 本地熱更新的速度不會受項目的大小影響太多,在大型項目中本地開發速度快。
Vite 的客戶端熱更新代碼是在 app.vue 文件編譯過程中,將代碼注入進去的。

六、Vite 和 vue-cli 的優缺點對比

vue-cli優缺點

vue-cli優點 vue-cli缺點
有很多成型項目,可靠 開發服務器速度與依賴數量成反比
完全兼容vue2
可綁定任何類型的依賴關係
插件生態系統完整

vite優缺點

vite優點 vite缺點
開發服務器比webpack快10倍以上 只能對(ES2015+)以上現代瀏覽器支持
將 code-splitting 作為優先事項 與 CommonJS 模塊不完全兼容
處於測試階段,僅支持 Vue 3
最小的腳手架不包括 Vuex、路由器等
不同的開發服務器與構建工具
Tags: