vite vue3 vite vue3
时间: 2025-06-07 12:46:19 浏览: 24
### Vite with Vue3 Setup and Usage
Vite 是一个现代化的前端构建工具,结合 Vue3 可以快速搭建高效的应用程序。以下是关于使用 Vite 和 Vue3 的详细设置和用法。
#### 1. 创建项目
首先需要安装 Vite 并创建一个新的 Vue3 项目。可以通过以下命令完成:
```bash
npm create vite@latest my-vue-app --template vue
cd my-vue-app
npm install
```
#### 2. 配置 Vite 插件
为了增强开发体验,可以引入一些插件。例如 `vite-plugin-vue-setup-extend` 插件支持在 `<script setup>` 中直接定义组件的 `name` 属性[^1]。
在 `vite.config.js` 文件中添加插件配置:
```javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
export default defineConfig({
plugins: [
vue(),
VueSetupExtend()
]
})
```
#### 3. 使用 Less 样式
如果希望在项目中使用 Less 编写样式,需要安装相关依赖并进行配置。安装 Less 和其 loader:
```bash
npm install less less-loader --save-dev
```
然后可以在 `.vue` 文件中直接使用 `<style lang="less">` 来编写样式[^1]。
#### 4. 集成 UI 框架
对于 UI 框架的选择,可以根据需求选择 Element Plus 或 Naive UI 等。以 Naive UI 为例,可以通过按需加载的方式引入组件,减少打包体积[^3]。
安装 Naive UI 和按需加载插件:
```bash
npm install naive-ui
npm install unplugin-vue-components -D
```
在 `vite.config.js` 中配置插件:
```javascript
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
Components({
resolvers: [NaiveUiResolver()]
})
]
})
```
#### 5. 组件定义与使用
Vue3 的 `<script setup>` 语法简化了组件的定义方式。可以直接在模板中使用组件而无需显式导入[^5]。
示例组件 `HelloWorld.vue`:
```vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script setup>
defineProps({
msg: String
})
</script>
<style lang="less">
.hello {
color: red;
}
</style>
```
#### 6. 构建与优化
在生产环境中,可以通过 Rollup 插件进行打包分析,确保资源优化[^3]。在 `vite.config.js` 中添加以下配置:
```javascript
import visualizer from 'rollup-plugin-visualizer'
export default defineConfig({
build: {
rollupOptions: {
plugins: [
visualizer({
open: true,
gzipSize: true,
brotliSize: true
})
]
}
}
})
```
---
###
阅读全文
相关推荐




















