一、推薦兩個外掛外掛
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: 'http://localhost:3333/',
changeOrigin: true,
ws: true,
rewrite: (pathStr) => pathStr.replace('/api', '')
},
},
},
3、按需引入element plus
- 安裝vite-plugin-style-import
yarn add vite-plugin-style-import -D
- 在專案根目錄下的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、路由器等 |
- | 不同的開發伺服器與構建工具 |