Vite 是一个由 Vue.js 作者尤雨溪开发的现代前端构建工具,它利用原生 ES 模块导入来提供更快的开发服务器启动时间和更快的热更新。以下是 Vite 的一些常用命令,可以帮助你管理和运行项目。
基础命令
安装 Vite
- 使用 npm:
1
npm install -g create-vite
- 使用 yarn:
1
yarn global add create-vite
- 使用 npm:
创建新项目
- 使用 npm:
1
npm create vite@latest my-vue-app --template vue
- 使用 yarn:
1
yarn create vite my-vue-app --template vue
可用的模板包括:
vue
:Vue 3 单文件组件 (SFC) 项目react
:React 项目preact
:Preact 项目vanilla
:纯 JavaScript 项目vanilla-ts
:纯 TypeScript 项目
- 使用 npm:
项目管理
安装项目依赖
- 使用 npm:
1
2cd my-vue-app
npm install - 使用 yarn:
1
2cd my-vue-app
yarn
- 使用 npm:
启动开发服务器
- 使用 npm:
1
npm run dev
- 使用 yarn:
1
yarn dev
这将启动 Vite 开发服务器,并在浏览器中打开项目。
- 使用 npm:
构建和部署
构建项目
- 使用 npm:
1
npm run build
- 使用 yarn:
1
yarn build
这将生成生产环境的静态文件,通常位于
dist/
目录下。- 使用 npm:
预览构建结果
- 使用 npm:
1
npm run preview
- 使用 yarn:
1
yarn preview
这将启动一个本地服务器来预览构建结果,方便在部署前进行检查。
- 使用 npm:
配置
编辑配置文件
- Vite 的配置文件通常是
vite.config.js
或vite.config.ts
。你可以在这个文件中配置各种选项,如别名、代理、插件等。
示例配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true,
proxy: {
'/api': 'http://localhost:3001',
},
},
resolve: {
alias: {
'@': '/src',
},
},
});- Vite 的配置文件通常是
插件管理
安装插件
- 使用 npm:
1
npm install @vitejs/plugin-vue
- 使用 yarn:
1
yarn add @vitejs/plugin-vue
在
vite.config.js
中使用插件:1
2
3
4
5
6import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
});- 使用 npm:
调试和日志
- 查看详细日志
- 启动开发服务器时,Vite 会显示详细的日志信息。如果需要更多调试信息,可以在
vite.config.js
中配置日志级别:1
2
3
4
5
6
7import { defineConfig } from 'vite';
export default defineConfig({
server: {
logLevel: 'info', // 可选值:'silent', 'error', 'warn', 'info', 'debug'
},
});
- 启动开发服务器时,Vite 会显示详细的日志信息。如果需要更多调试信息,可以在
其他实用命令
生成类型定义文件
- 如果你在使用 TypeScript,可以生成类型定义文件:
1
npx tsc --init
- 如果你在使用 TypeScript,可以生成类型定义文件:
运行自定义脚本
- 你可以在
package.json
中定义自定义脚本:1
2
3
4
5
6
7
8{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint ."
}
}
运行自定义脚本:
1
npm run lint
- 你可以在
示例
假设你有一个名为 my-vue-app
的 Vite 项目,你可以使用以下命令来管理和运行项目:
创建新项目
1
npm create vite@latest my-vue-app --template vue
安装项目依赖
1
2cd my-vue-app
npm install启动开发服务器
1
npm run dev
构建项目
1
npm run build
预览构建结果
1
npm run preview
编辑配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true,
proxy: {
'/api': 'http://localhost:3001',
},
},
resolve: {
alias: {
'@': '/src',
},
},
});
这些命令涵盖了 Vite 的大多数常用功能。