您好,登录后才能下订单哦!
# 怎么用Vite+Vue3.0+TS+Element-Plus搭建项目
## 前言
随着前端技术的快速发展,Vue3.0凭借其优秀的Composition API和更好的性能表现,已经成为现代前端开发的首选框架之一。而Vite作为新一代前端构建工具,凭借其极快的启动速度和热更新能力,正在逐步取代Webpack成为Vue项目的标配构建工具。本文将详细介绍如何使用Vite+Vue3.0+TypeScript+Element-Plus搭建一个完整的前端项目。
## 环境准备
在开始项目搭建之前,请确保你的开发环境满足以下要求:
- Node.js 版本 >= 14.18(推荐使用16.x LTS版本)
- npm 版本 >= 6.x 或 yarn >= 1.22
- 代码编辑器(推荐VS Code)
### 检查Node.js版本
```bash
node -v
# 应该显示 v14.18.x 或更高版本
npm -v
# 应该显示 6.x 或更高版本
如果版本过低,建议通过nvm(Mac/Linux)或nvm-windows(Windows)来管理Node.js版本。
Vite提供了多种模板,我们将使用Vue+TypeScript模板来初始化项目。
npm create vite@latest my-vue-app -- --template vue-ts
cd my-vue-app
npm install
npm run dev
此时,你应该能在浏览器中看到Vite+Vue3的欢迎页面,访问地址通常是http://localhost:3000
。
让我们先了解一下Vite创建的默认项目结构:
my-vue-app/
├── node_modules/ # 项目依赖
├── public/ # 静态资源目录
├── src/ # 源代码目录
│ ├── assets/ # 静态资源(图片、字体等)
│ ├── components/ # Vue组件
│ ├── App.vue # 根组件
│ ├── main.ts # 应用入口文件
│ ├── vite-env.d.ts # Vite环境类型声明
│ └── style.css # 全局样式
├── index.html # 应用入口HTML文件
├── package.json # 项目配置文件
├── tsconfig.json # TypeScript配置
└── vite.config.ts # Vite配置
虽然Vite开箱即用,但我们还是需要根据项目需求进行一些配置调整。打开vite.config.ts
文件:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src') // 设置@别名指向src目录
}
},
server: {
port: 8080, // 设置开发服务器端口
open: true, // 自动打开浏览器
proxy: { // 配置代理
'/api': {
target: 'http://your-api-server.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
Vite已经为我们配置好了TypeScript,但我们可以进一步完善TS配置。
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
在src
目录下创建shims-vue.d.ts
文件,为.vue文件添加类型支持:
declare module '*.vue' {
import { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
Element Plus是Vue3版本的Element UI组件库,下面我们来集成它。
npm install element-plus
# 或者使用yarn
yarn add element-plus
修改main.ts
文件:
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
首先安装unplugin-vue-components和unplugin-auto-import:
npm install -D unplugin-vue-components unplugin-auto-import
然后修改vite.config.ts:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
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: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
})
这样我们就可以直接在组件中使用Element Plus的组件,而无需手动导入。
为了更好地组织代码,我们可以对项目结构进行优化:
src/
├── api/ # API请求
├── assets/ # 静态资源
├── components/ # 公共组件
├── composables/ # 组合式函数
├── router/ # 路由配置
├── store/ # 状态管理
├── utils/ # 工具函数
├── views/ # 页面组件
├── App.vue # 根组件
└── main.ts # 入口文件
安装Vue Router:
npm install vue-router@4
创建src/router/index.ts
:
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
export default router
修改main.ts
:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
安装Pinia(Vue官方推荐的状态管理库):
npm install pinia
创建src/store/index.ts
:
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
创建示例store src/store/user.ts
:
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: 'Guest',
isLogin: false
}),
actions: {
login(name: string) {
this.name = name
this.isLogin = true
},
logout() {
this.name = 'Guest'
this.isLogin = false
}
}
})
修改main.ts
:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './store'
const app = createApp(App)
app.use(router)
app.use(pinia)
app.mount('#app')
npm install -D sass
在src/assets
目录下创建scss
文件夹,并添加以下文件:
_variables.scss
- 全局变量_mixins.scss
- 混合index.scss
- 主样式文件在main.ts
中引入全局样式:
import '@/assets/scss/index.scss'
创建src/assets/scss/element-variables.scss
:
/* 重写Element Plus变量 */
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
$colors: (
'primary': (
'base': #409EFF,
),
),
);
然后在vite.config.ts
中配置:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/assets/scss/element-variables.scss" as *;`,
}
}
},
plugins: [
vue(),
Components({
resolvers: [
ElementPlusResolver({
importStyle: "sass",
}),
],
}),
],
})
为了保证代码质量和一致性,我们需要配置ESLint和Prettier。
npm install -D eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier
创建.eslintrc.js
:
module.exports = {
root: true,
env: {
node: true,
browser: true,
es2021: true,
},
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'prettier/prettier': [
'error',
{
endOfLine: 'auto',
},
],
},
}
创建.eslintignore
:
node_modules
dist
*.md
*.json
*.d.ts
创建.prettierrc.js
:
module.exports = {
printWidth: 100,
tabWidth: 2,
useTabs: false,
semi: false,
singleQuote: true,
quoteProps: 'as-needed',
jsxSingleQuote: false,
trailingComma: 'es5',
bracketSpacing: true,
bracketSameLine: false,
arrowParens: 'always',
endOfLine: 'lf',
}
在package.json
中添加:
"scripts": {
"lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix",
"format": "prettier --write ."
}
Vite使用import.meta.env
来访问环境变量。
.env
- 所有环境通用.env.development
- 开发环境.env.production
- 生产环境示例.env.development
:
VITE_API_BASE_URL=/api
VITE_APP_TITLE=Development App
在代码中可以通过import.meta.env.VITE_API_BASE_URL
访问。
在src/env.d.ts
中添加:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_APP_TITLE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
npm run build
构建结果会生成在dist
目录下。
npm run preview
在vite.config.ts
中:
export default defineConfig({
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
assetsInlineLimit: 4096, // 小于此值的资源将内联为base64
cssCodeSplit: true, // 启用CSS代码分割
sourcemap: false, // 生产环境不生成sourcemap
minify: 'terser', // 使用terser进行代码压缩
terserOptions: {
compress: {
drop_console: true, // 移除console
drop_debugger: true // 移除debugger
}
},
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString()
}
}
}
}
}
})
在vite.config.ts
中添加:
server: {
watch: {
usePolling: true // 解决WSL2中热更新问题
}
}
安装Element Plus图标:
npm install @element-plus/icons-vue
使用示例:
<template>
<el-icon><Edit /></el-icon>
</template>
<script setup>
import { Edit } from '@element-plus/icons-vue'
</script>
如果遇到类型报错,可以尝试以下方法:
tsconfig.json
配置是否正确// @ts-ignore
临时忽略错误(不推荐长期使用)Vite默认支持代码分割,但我们可以进一步优化:
build: {
rollupOptions: {
output: {
manualChunks: {
'element-plus': ['element-plus'],
'vue': ['vue', 'vue-router', 'pinia']
}
}
}
}
安装vite-plugin-imagemin
:
npm install -D vite-plugin-imagemin
配置:
import viteImagemin from 'vite-plugin-imagemin'
export default defineConfig({
plugins: [
viteImagemin({
gifsicle: { optimizationLevel: 7, interlaced: false },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 20 },
pngquant: { quality: [0.8, 0.9], speed: 4 },
svgo: {
plugins: [
{ name: 'removeViewBox' },
{ name: 'removeEmptyAttrs', active: false }
]
}
})
]
})
安装vite-plugin-cdn-import
:
npm install -D vite-plugin-cdn-import
配置示例:
import importToCDN from 'vite-plugin-cdn-import'
export default defineConfig({
plugins: [
importToCDN({
modules: [
{
name: 'vue',
var: 'Vue',
path: 'https://cdn.jsdelivr.net/npm/vue@3.2.31/dist/vue.global.min.js'
},
{
name: 'element-plus',
var: 'ElementPlus',
path: 'https://cdn.jsdelivr.net/npm/element-plus@2.0.5/dist/index.full.min.js',
css: 'https://cdn.jsdelivr.net/npm/element-plus@2.0.5/dist/index.css'
}
]
})
]
})
通过本文的详细步骤,我们已经成功搭建了一个基于Vite+Vue3+TypeScript+Element Plus的现代化前端项目。这种技术组合不仅提供了极佳的开发体验,还能保证应用的性能和可维护性。在实际项目中,你还可以根据需要集成更多工具和库,如测试框架、国际化方案等。
希望本文能帮助你快速上手Vite和Vue3的开发,为你的项目开发提供坚实的基础。Happy coding! “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。