vite+vue3項目初始化搭建的實現(xiàn)步驟
vite+vue3項目初始化搭建
"nodejs": v18.19.0
"pnpm": 8.15.0
"vue": v3.4.21
"vite": v5.2.0
1.創(chuàng)建項目
pnpm create vite@latest
項目名字:gd_web
選擇框架:Vue3
選擇語言:JavaScript
進入項目:cd gd_web
安裝依賴: pnpm i
啟動項目:pnpm run dev
2.配置.editorconfig
# https://editorconfig.org # 根目錄配置,表示當前目錄是編輯器配置的根目錄 root = true [*] # 對所有文件應用以下配置 charset = utf-8 # 使用 UTF-8 編碼 indent_style = space # 使用空格進行縮進 indent_size = 4 # 每個縮進級別使用 4 個空格 end_of_line = lf # 使用 LF(Linux 和 macOS 的換行符) insert_final_newline = true # 在文件末尾插入一行空白 trim_trailing_whitespace = true # 自動刪除行末尾的空白字符 [*.md] # 對擴展名為 .md 的 Markdown 文件應用以下配置 insert_final_newline = false # 不在文件末尾插入一行空白 trim_trailing_whitespace = false # 不自動刪除行末尾的空白字符
3.別名配置
在開發(fā)項目的時候文件與文件關系可能很復雜,因此我們需要給src文件夾配置一個別名?。?!
在vite.config.js文件中:
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
// 配置別名
alias: {
"@": path.resolve("./src") // 相對路徑別名配置,使用 @ 代替 src
},
//extensions數(shù)組的意思是在import組件的時候自動補全.vue等文件后綴
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
}
})
如果不能識別path模塊
pnpm install @types/node --save-dev
配置完成后,我們發(fā)現(xiàn)我們 '@'之后沒有提示,這個時候我們在根目錄創(chuàng)建jsconfig.json文件
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": [
"src/*"
]
}
},
"exclude": [
"node_modules"
]
}
4.環(huán)境變量的配置
項目開發(fā)過程中,至少會經(jīng)歷開發(fā)環(huán)境、測試環(huán)境和生產(chǎn)環(huán)境(即正式環(huán)境)三個階段。不同階段請求的狀態(tài)(如接口地址等)不盡相同,若手動切換接口地址是相當繁瑣且易出錯的。于是環(huán)境變量配置的需求就應運而生,我們只需做簡單的配置,把環(huán)境狀態(tài)切換的工作交給代碼。
開發(fā)環(huán)境(development)
顧名思義,開發(fā)使用的環(huán)境,每位開發(fā)人員在自己的dev分支上干活,開發(fā)到一定程度,同事會合并代碼,進行聯(lián)調(diào)。
測試環(huán)境(testing)
測試同事干活的環(huán)境啦,一般會由測試同事自己來部署,然后在此環(huán)境進行測試
生產(chǎn)環(huán)境(production)
生產(chǎn)環(huán)境是指正式提供對外服務的,一般會關掉錯誤報告,打開錯誤日志。(正式提供給客戶使用的環(huán)境。)
注意:一般情況下,一個環(huán)境對應一臺服務器,也有的公司開發(fā)與測試環(huán)境是一臺服務器?。?!
項目根目錄分別添加 開發(fā)、生產(chǎn)和測試環(huán)境的文件!
.env.development .env.production .env.test
文件內(nèi)容:
# 變量必須以 VITE_ 為前綴才能暴露給外部讀取 NODE_ENV = 'development' VITE_APP_TITLE = '項目名字' VITE_APP_BASE_API = '/dev-api' VITE_SERVE = 'http://127.0.0.1:8990'
# 變量必須以 VITE_ 為前綴才能暴露給外部讀取 NODE_ENV = 'production' VITE_APP_TITLE = '項目名字' VITE_APP_BASE_API = '/prod-api' VITE_SERVE = 'http://127.0.0.1:8990'
# 變量必須以 VITE_ 為前綴才能暴露給外部讀取 NODE_ENV = 'test' VITE_APP_TITLE = '項目名字' VITE_APP_BASE_API = '/test-api' VITE_SERVE = 'http://127.0.0.1:8990'
配置運行命令:package.json
"scripts": {
"dev": "pnpm vite --open",
"build:test": "pnpm vite build --mode test",
"build:pro": "pnpm vite build --mode production",
"preview": "vite preview"
},
通過import.meta.env獲取環(huán)境變量
5.安裝css預處理器sass
pnpm install -D sass sass-loader
組件中使用:
<style scoped lang="scss"></style>
全局樣式定義:
在src/styles目錄下創(chuàng)建一個index.scss文件;
當然項目中需要用到清除默認樣式,可以在index.scss引入reset.scss
reset.scss
// index.scss文件中引入 @import "reset.scss";
在入口文件中引入全局樣式:
import '@/styles/index.scss'
在src/styles/index.scss全局樣式文件中沒有辦法使用 變量 . 因此需要給項目中引入全局變量 變量.因此需要給項目中引入全局變量 變量.因此需要給項目中引入全局變量.
在style/variable.scss創(chuàng)建一個variable.scss文件!
在vite.config.js文件配置如下:
export default defineConfig((config) => {
//配置scss全局變量
css: {
preprocessorOptions: {
scss: {
javascriptEnabled: true,
additionalData: '@import "./src/styles/variable.scss";'
}
}
}
}
6.集成Element-plus
安裝:
pnpm install element-plus --save
配置自動導入: 需要安裝unplugin-vue-components 和 unplugin-auto-import這兩款插件
pnpm install -D unplugin-vue-components unplugin-auto-import
在vite配置文件中添加:
// vite.config.ts
import {defineConfig} from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
export default defineConfig({
// ...
plugins: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
// 自動導入 Vue 相關函數(shù),如:ref, reactive, toRef 等
imports: ['vue'],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
// ...
],
})
配置Element-plus 組件內(nèi)容中文顯示:
main.js文件中添加
// 引入element-plus樣式
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import locale from 'element-plus/dist/locale/zh-cn.mjs'
app.use(ElementPlus, {locale})
Element-plus icon圖標全局使用
pnpm install @element-plus/icons-vue
注冊所有圖標,在component/index.js文件中
從 @element-plus/icons-vue 中導入所有圖標并進行全局注冊
// 引入element-plus提供的所有圖標
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// 對外暴露插件對象
export default {
// 必須叫做install方法,會有一個APP對象傳參;
// 在入口文件引入使用,會自動執(zhí)行該方法
install(app) {
// 將element-plus提供的圖標注冊為全局組件
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
},
}
在入口文件引入src/index.js文件,通過app.use方法安裝自定義插件
// 注冊全局組件 import gloablComponent from '@/components/index.js' app.use(gloablComponent)
使用:詳細見官網(wǎng)
<!-- 使用 el-icon 為 SVG 圖標提供屬性 -->
<template>
<div>
<el-icon :size="size" :color="color">
<Edit/>
</el-icon>
<!-- 或者獨立使用它,不從父級獲取屬性 -->
<Edit/>
</div>
</template>
7.SVG圖標配置
安裝SVG依賴插件
pnpm install vite-plugin-svg-icons -D
在vite.config.js中配置插件
plugins: [
// ...
// 配置自定義SVG 圖標
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
// ...
]
入口文件(main.js)導入
// 注冊SVG圖標 import 'virtual:svg-icons-register'
將svg封裝為全局組件
因為項目很多模塊需要使用圖標,因此把它封裝為全局組件?。。?/p>
在src/components目錄下創(chuàng)建一個SvgIcon組件:代表如下
<template>
<div>
<svg :style="{ width: width, height: height }">
<use :xlink:href="prefix + name" rel="external nofollow" :fill="color"></use>
</svg>
</div>
</template>
<script setup>
defineProps({
//xlink:href屬性值的前綴
prefix: {
type: String,
default: '#icon-'
},
//svg矢量圖的名字
name: String,
//svg圖標的顏色
color: {
type: String,
default: ""
},
//svg寬度
width: {
type: String,
default: '16px'
},
//svg高度
height: {
type: String,
default: '16px'
}
})
</script>
<style scoped></style>
在src/components文件夾目錄下創(chuàng)建一個index.js文件:用于注冊components文件夾內(nèi)部全部全局組件?。?!
import SvgIcon from './SvgIcon'
const components = { SvgIcon }
// 引入element-plus提供的所有圖標
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// 對外暴露插件對象
export default {
// 必須叫做install方法,會有一個APP對象傳參;
// 在入口文件引入使用,會自動執(zhí)行該方法
install(app) {
//注冊全局SVG組件
Object.keys(components).forEach((key) => {
app.component(key, components[key])
})
// 將element-plus提供的圖標注冊為全局組件
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
},
}
在入口文件引入src/index.js文件,通過app.use方法安裝自定義插件
// 注冊全局組件 import globalComponent from '@/components/index.js' app.use(globalComponent)
8.配置封裝axios
安裝axios:
pnpm install axios
在根目錄下創(chuàng)建utils/request.js
import axios from "axios";
import {ElMessage} from "element-plus";
//創(chuàng)建axios實例
let request = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API,
timeout: 5000
})
//請求攔截器
request.interceptors.request.use(config => {
return config;
});
//響應攔截器
request.interceptors.response.use((response) => {
return response.data;
}, (error) => {
//處理網(wǎng)絡錯誤
let msg = '';
let status = error.response.status;
switch (status) {
case 401:
msg = "token過期";
break;
case 403:
msg = '無權訪問';
break;
case 404:
msg = "請求地址錯誤";
break;
case 500:
msg = "服務器出現(xiàn)問題";
break;
default:
msg = "無網(wǎng)絡";
}
ElMessage({
type: 'error',
message: msg
})
return Promise.reject(error);
});
export default request;
9.api接口統(tǒng)一管理
在開發(fā)項目的時候,接口可能很多需要統(tǒng)一管理。在src目錄下去創(chuàng)建api文件夾去統(tǒng)一管理項目的接口;
例如:
//統(tǒng)一管理用戶相關的接口
import request from '../utils/request.js'
//項目用戶相關的請求地址
const API = {
LOGIN_URL: '/admin/acl/index/login',
USERINFO_URL: '/admin/acl/index/info',
LOGOUT_URL: '/admin/acl/index/logout',
}
//登錄接口
export const reqLogin = (data) => request.post(API.LOGIN_URL, data)
//獲取用戶信息
export const reqUserInfo = () => request.get(API.USERINFO_URL)
//退出登錄
export const reqLogout = () => request.post(API.LOGOUT_URL)
10.配置vue-router
安裝:
pnpm install vue-router@4
1.創(chuàng)建src/router/index.js文件,使用路由懶加載,優(yōu)化訪問性能
import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/home.vue') // 建議進行路由懶加載,優(yōu)化訪問性能
},
{
path: '/about',
name: 'About',
component: () => import('../views/about.vue')
}
]
const router = createRouter({
// history: createWebHistory(), // 使用history模式
history: createWebHashHistory(), // 使用hash模式
routes
})
export default router
2.在App.vue 文件中使用router-view 組件,路由匹配到組件會通過router-view 組件進行渲染。
<template>
<div id="nav">
<router-link to="/">Home</router-link>
|
<router-link to="/about">About</router-link>
</div>
<router-view></router-view>
</template>
3.main.js中引入router
// ... // 引入路由 import router from './router/index.js' app.use(router) // ...
11.配置pinia
安裝:
pnpm install pinia
在main.js文件中引入:
// 引入pinia
import {createPinia} from 'pinia'
app.use(createPinia())
創(chuàng)建文件夾src/stores在該文件夾中管理一些公用數(shù)據(jù),用戶數(shù)據(jù)user.js,購物車數(shù)據(jù)等
定義
//定義關于counter的store
import {defineStore} from 'pinia'
/*defineStore 是需要傳參數(shù)的,其中第一個參數(shù)是id,就是一個唯一的值,
簡單點說就可以理解成是一個命名空間.
第二個參數(shù)就是一個對象,里面有三個模塊需要處理,第一個是 state,
第二個是 getters,第三個是 actions。
*/
const useCounter = defineStore("counter", {
state: () => ({
count: 66,
}),
// getters 類似于 vue 里面的計算屬性,可以對已有的數(shù)據(jù)進行修飾。
// 不管調(diào)用多少次,getters中的函數(shù)只會執(zhí)行一次,且都會緩存。
getters: {},
actions: {}
})
//暴露這個useCounter模塊
export default useCounter
使用
<script setup> // 首先需要引入一下我們剛剛創(chuàng)建的store import useCounter from '../stores/counter.js' // 因為是個方法,所以我們得調(diào)用一下 // 注意獲取數(shù)據(jù)后不支持結(jié)構(gòu),結(jié)構(gòu)則失去響應式 const counterStore = useCounter() console.log(counterStore.count) </script>
pinia提供了一個函數(shù)storeToRefs解決。引用官方API storeToRef 作用就是把結(jié)構(gòu)的數(shù)據(jù)使用ref做代理
import {storeToRefs} from 'pinia'
const counterStore = useCounter()
// 結(jié)構(gòu)仍為響應式數(shù)據(jù)
const {count} = storeToRefs(counterStore)
12.Proxy代理配置
import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
// https://vitejs.dev/config/
export default defineConfig(({command, mode}) => {
// 根據(jù)當前工作目錄中的 `mode` 加載 .env 文件
// 設置第三個參數(shù)為 '' 來加載所有環(huán)境變量,而不管是否有 `VITE_` 前綴。
const env = loadEnv(mode, process.cwd())
// console.log(env)
return {
base: env.VITE_USER_NODE_ENV === 'production' ? './' : '/',
plugins: [
vue(),
// 配置自定義SVG圖標
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
// AutoImport({
// resolvers: [ElementPlusResolver()],
// // 自動導入 Vue 相關函數(shù),如:ref, reactive, toRef 等
// imports: ['vue'],
// }),
// Components({
// resolvers: [ElementPlusResolver()],
// }),
],
resolve: {
// 配置別名
alias: {
"@": path.resolve("./src") // 相對路徑別名配置,使用 @ 代替 src
},
//extensions數(shù)組的意思是在import組件的時候自動補全.vue等文件后綴
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
// 配置scss變量
css: {
preprocessorOptions: {
scss: {
javascriptEnabled: true,
additionalData: '@import "./src/styles/variable.scss";'
}
}
},
// 代理跨域
server: {
// open: true, //啟動項目自動彈出瀏覽器
hmr: true, //開啟熱加載
host: false, //監(jiān)聽所有地址
port: 6688, //啟動端口
strictPort: false, //設為 true 時若端口已被占用則會直接退出,而不是嘗試下一個可用端口
https: false, // 是否開啟https
//proxy: createProxy(env.VITE_APP_API_HOST),
proxy: {
[env.VITE_APP_BASE_API]: {
// 獲取數(shù)據(jù)的服務器地址設置
target: env.VITE_SERVE,
//開啟代理跨域
changeOrigin: true,
// secure:安全的
// 如果是https接口,需要配置這個參數(shù)
secure: false,
// 路徑重寫
// 將請求路徑中的 '/api' 替換為 ''
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
}
})
到此這篇關于vite+vue3項目初始化搭建的實現(xiàn)步驟的文章就介紹到這了,更多相關vite+vue3初始化搭建內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue項目中v-bind動態(tài)綁定src路徑不成功問題及解決
這篇文章主要介紹了Vue項目中v-bind動態(tài)綁定src路徑不成功問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

