Vite 開發(fā)快速入門
逆鋒起筆關注后回復編程pdf
作者:xiangzhihong
來源:SegmentFault 思否社區(qū)
一、Vite簡介
Vite (法語意為 "快速的",發(fā)音 /vit/) 是一種面向現(xiàn)代瀏覽器的一個更輕、更快的前端構建工具,能夠顯著提升前端的開發(fā)體驗。除了Vite外,前端著名的構建工具還有Webpack和Gulp。目前,Vite已經(jīng)發(fā)布了Vite2,Vite全新的插件架構、絲滑的開發(fā)體驗,可以和Vue3的完美結合。
1.1 Vite組成
Vite構建工具由兩部分組成:
一個開發(fā)服務器,它基于原生 ES 模塊提供了豐富的內(nèi)建功能,如模塊熱更新(HMR)。
一套構建指令,它使用 Rollup 打包你的代碼,并且它是預配置的,可以輸出用于生產(chǎn)環(huán)境的優(yōu)化過的靜態(tài)資源。
1.2 瀏覽器支持
開發(fā)環(huán)境中:Vite需要在支持原生 ES 模塊動態(tài)導入的瀏覽器中使用。
生產(chǎn)環(huán)境中:默認支持的瀏覽器需要支持 通過腳本標簽來引入原生 ES 模塊 。可以通過官方插件 @vitejs/plugin-legacy 支持舊瀏覽器。
二、環(huán)境搭建
2.1 創(chuàng)建項目
npm init vite@latest 項目名
yarn create vite 項目名
# 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
2.2 集成Vue-Router
2.2.1 安裝配置Vue-Router
//npm
npm install vue-router@next --save
//yarn
yarn add vue-router@next --save
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: () => import('views/home.vue') }
]
});
export default router
import router from './router';
createApp(App).use(router).mount("#app");
2.2.2 新增路由頁面
routes: [
{
path: "/home",
name: "Home",
alias: "/",
component: () => import("../pages/Home.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 集成Vuex
//npm
npm install vuex@next --save
//yarn
yarn add vuex@next --save
import { createStore } from "vuex";
const store = createStore({
modules: {
home: {
namespaced: true,
state: {
count: 1
},
mutations: {
add(state){
state.count++;
}
}
}
}
})
export default store;
import { createApp } from 'vue';
import App from './App.vue';
import store from "./store";
const app = createApp(App);
app.use(store);
app.mount('#app');
<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>
2.4 集成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 -D
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
{
"root": true,
"env": {
"browser": true,
"node": true,
"es2021": true
},
"extends": [
"plugin:vue/vue3-recommended",
"eslint:recommended",
"@vue/typescript/recommended"
],
"parserOptions": {
"ecmaVersion": 2021
}
}
{
"lint": "eslint --ext src/**/*.{ts,vue} --no-error-on-unmatched-pattern"
}
yarn lint就可以了,可以通過eslint完成格式的校驗了。不過,我們在執(zhí)行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
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' },
]
}
});
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
//以下為需要添加內(nèi)容
"types": ["vite/client", "jest"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
]
}
2.6 集成element-plus
npm install element-plus --save
2.6.1 引入element-plus
import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
npm install babel-plugin-component --save
{
"plugins": [
[
"component",
{
"libraryName": "element-plus",
"styleLibraryName": "theme-chalk"
}
]
]
}
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 添加配置
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
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}`;
},
}
]
})
],
/**
* 在生產(chǎn)中服務時的基本公共路徑。
* @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")
},
}
})
三、數(shù)據(jù)請求
//npm
npm insall axios -save
//yarn
yarn add axios -save
import axios from 'axios';
let request = axios.create({
baseURL: 'http://localhost:3555/api'
})
export default request;
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()
})
}
}
逆鋒起筆是一個專注于程序員圈子的技術平臺,你可以收獲最新技術動態(tài)、最新內(nèi)測資格、BAT等大廠大佬的經(jīng)驗、增長自身、學習資料、職業(yè)路線、賺錢思維,微信搜索逆鋒起筆關注!

評論
圖片
表情
