Vite已經出來很久了,新版本也比較穩定,有沒有打算入手一下,推薦下面這篇文章。
Vite (法語意為 "快速的",發音 /vit/) 是一種面向現代瀏覽器的一個更輕、更快的前端構建工具,能夠顯著提升前端的開發體驗。除了Vite外,前端著名的構建工具還有Webpack和Gulp。目前,Vite已經發布了Vite2,Vite全新的插件架構、絲滑的開發體驗,可以和Vue3的完美結合。
1.1 Vite組成Vite構建工具由兩部分組成:
總的來說,Vite希望提供開箱即用的配置,同時它的插件API和JavaScript API帶來了高度的可擴展性。不過,相比Vue-cli配置來說,Vite構建的項目還是有很多的配置需要開發者自己進行處理。1.2 瀏覽器支持二、環境搭建2.1 創建項目根據Vite官網介紹,我們可以使用npm或yarn來初始化Vite項目,並且Node.js的版本需要 >= 12.0.0。除此之外,還可以通過附加的命令行選項直接指定項目名稱和模板。例如,要構建一個 Vite + Vue 項目,命令如下:# npm 6.x
npm init @vitejs/app my-vue-app --template vue
# npm 7+, 需要額外的雙橫線:
npm init @vitejs/app my-vue-app -- --template vue
# yarn
yarn create @vitejs/app my-vue-app --template vue
輸入完命令之後,按照提示操作即可。如果項目需要支持TypeScript,可以在初始化項目的時候選擇vue-ts。項目創建好之後,可以發現Vite所創建好的項目其實與使用Vue-cli所創建的項目目錄結構其實是差不多的。
2.2 集成Vue-Router2.2.1 安裝配置Vue-RouterVue-Router作為大多數項目必不可少的路由工具,已經被大多數的前端項目所使用,Vue-Router可以讓構建單頁面應用變得更加的容易。首先,在項目中安裝Vue-Router,安裝命令如下://npm
npm install vue-router@next --save
//yarn
yarn add vue-router@next --save
安裝完成之後,在src目錄下創建一個文件夾router/index.ts,然後添加如下一些配置:import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: () => import('views/home.vue') }
]
});
export default router
然後,我們在main.ts文件中引入Vue-Router,如下所示。import router from './router';
createApp(App).use(router).mount("#app");
2.2.2 新增路由頁面
為了方便掩飾,我們再新增兩個路由頁面。熟悉,創建pages文件夾,把需要展示的頁面創建完成。然後,我們在router/index.ts註冊我們新增的頁面,如下所示。routes: [
{
path: "/home",
name: "Home",
alias: "/",
component: () => import("../pages/Home.vue")
},
]
接下來,我們再修改一下App.vue的代碼,如下所示。<template>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'App'
})
</script>
接下來啟動服務,就可以看到所配置的頁面了,並且點擊還能夠跳轉到對應的頁面。
2.3 集成VuexVuex 是一個專為 Vue.js 應用程式開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。Vuex 也集成到 Vue 的官方調試工具 devtools extension (opens new window),提供了諸如零配置的 time-travel 調試、狀態快照導入導出等高級調試功能。使用Vuex之前,需要先安裝Vuex插件,如下所示。//npm
npm install vuex@next --save
//yarn
yarn add vuex@next --save
安裝完成之後,需要先初始化Vuex。首先,創建一個store/index.ts文件,添加如下代碼。import { createStore } from "vuex";
const store = createStore({
modules: {
home: {
namespaced: true,
state: {
count: 1
},
mutations: {
add(state){
state.count++;
}
}
}
}
})
export default store;
上面的代碼作用就是實現一個簡單的自加功能。然後,我們在main.js文件中引入Vuex。import { createApp } from 'vue';
import App from './App.vue';
import store from "./store";
const app = createApp(App);
app.use(store);
app.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();
const count = computed(() => store.state.home.count);
const handleClick = () => {
store.commit('home/add');
};
return {
handleClick,
count
};
}
})
</script>
上面的代碼實現的就是一個簡單的自加功能,和默認示例工程的效果事一樣的,只不過我們使用Vuex。
2.4 集成EslintESLint是一個用來識別 ECMAScript語法, 並且按照規則給出報告的代碼檢測工具,使用它可以避免低級錯誤和統一代碼的風格。集成Eslint需要安裝如下一些插件: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 -Dyarn 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"
}
接下來運行一下yarn lint就可以了,可以通過eslint完成格式的校驗了。不過,我們在執行yarn lint的時候會把所有的文件全部都校驗一次,如果有很多文件的話,那麼校驗起來速度將會很慢,此時,我們一般只在git提交的時候才對修改的文件進行eslint校驗,那麼我們可以這麼做。
那就需要使用 lint-staged插件。//npm
npm install lint-staged -D
//yarn
yarn add lint-staged --dev{
"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 ."
},
}
2.5 配置alias
在過去使用vue-cli的時候,我們總是使用@去引入某些文件,由於Vite沒有提供類似的配置,所以我們需要手動的對其進行相關配置,才能繼續使用@符號去快捷的引入文件。首先,我們需要修改vite.config.ts的配置。import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { join } from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
find: '@',
replacement: '/src',
},
{ find: 'views', replacement: '/src/views' },
{ find: 'components', replacement: '/src/components' },
]
}
});
然後,我們在修改tsconfig.json文件,如下。{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
//以下為需要添加內容
"types": ["vite/client", "jest"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
]
}
2.6 集成element-plus
Element Plus是由餓了麼大前端團隊開源出品的一套為開發者、設計師和產品經理準備的基於 Vue 3.0 的組件庫,可以幫助開發者快速的開發網站,如果你使用過element-ui,那麼可以快速的過渡到element-plus。除了element-plus,支持Vue 3.0 的UI框架還有很多。首先,在項目的根目錄下安裝element-plus,命令如下:npm install element-plus --save
2.6.1 引入element-plus
我們可以引入整個 element-plus,也可以根據需要僅引入部分組件。如果是全部引入,只需要在main.js 添加如下代碼即可。import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
如果為了減小項目的包體積,那麼只需要引入對應的功能組件即可。首先,安裝 babel-plugin-component插件,如下所示。npm install babel-plugin-component --save{
"plugins": [
[
"component",
{
"libraryName": "element-plus",
"styleLibraryName": "theme-chalk"
}
]
]
}
如果我們只需要引入部分組件,比如 Button 和 Select組件,那麼需要在 main.js 中引入對應的組件即可,如下所示。import { createApp } from 'vue'
import { store, key } from './store';
import router from "./router";
import { ElButton, ElSelect } from 'element-plus';
import App from './App.vue';
import './index.css'
const app = createApp(App)
app.component(ElButton.name, ElButton);
app.component(ElSelect.name, ElSelect);
/* 或者
* app.use(ElButton)
* app.use(ElSelect)
*/
app.use(store, key)
app.use(router)
app.mount('#app')
2.6.2 添加配置
引入 Element Plus後,我們可以添加一個全局配置對象。該對象目前支持 size 與 zIndex 欄位。size 用於改變組件的默認尺寸,zIndex 設置彈框的初始 z-index。以下是兩種不同的引入方式:import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import App from './App.vue';
const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000 });import { createApp } from 'vue'
import { ElButton } from 'element-plus';
import App from './App.vue';
const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.use(ElButton);
2.6.3 配置proxy 和 alias
如果要在Vite中使用alias別名配置和proxy代理配置,那麼需要在vite.config.ts文件中進行單獨的配置。import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
styleImport({
libs: [
{
libraryName: 'element-plus',
esModule: true,
ensureStyleFile: true,
resolveStyle: (name) => {
return `element-plus/lib/theme-chalk/${name}.css`;
},
resolveComponent: (name) => {
return `element-plus/lib/${name}`;
},
}
]
})
],
/**
* 在生產中服務時的基本公共路徑。
* @default '/'
*/
base: './',
/**
* 與「根」相關的目錄,構建輸出將放在其中。如果目錄存在,它將在構建之前被刪除。
* @default 'dist'
*/
// outDir: 'dist',
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', '')
},
},
},
resolve: {
// 導入文件夾別名
alias: {
'@': path.resolve(__dirname, './src'),
views: path.resolve(__dirname, './src/views'),
components: path.resolve(__dirname, './src/components'),
utils: path.resolve(__dirname, './src/utils'),
less: path.resolve(__dirname, "./src/less"),
assets: path.resolve(__dirname, "./src/assets"),
com: path.resolve(__dirname, "./src/components"),
store: path.resolve(__dirname, "./src/store"),
mixins: path.resolve(__dirname, "./src/mixins")
},
}
})
其中,vite-plugin-style-import是一個可以按需引入樣式的庫。
三、數據請求Vue本身是不支持ajax調用的,如果需要執行網絡請求,那麼就需要藉助一些工具,如superagent和axios。不過,Vue開發使用得比較多的還是axios。//npm
npm insall axios -save
//yarn
yarn add axios -save
然後,新建一個request.ts,添加如下的代碼。import axios from 'axios';
let request = axios.create({
baseURL: 'http://localhost:3555/api'
})
export default request;
然後,在新建一個index.ts,用來處理具體的網絡請求,比如:import request from "./axios";
export const getUrl = () => {
return request({
url: "/users/test" // 請求地址
})
}
export default { getUrl };import { getUrl } from "../api/index"
export default {
setup() {
const getUrls = async() =>{
const res = await getUrl()
console.log(res)
}
onMounted(() => {
getUrls()
})
}
}關於本文
作者:xiangzhihong
來源:SegmentFault 思否社區