1. 什么是 Vite?
Vite 是一个现代化的前端构建工具,由 Vue.js 的作者尤雨溪开发。Vite 旨在提供更快的开发体验,特别是在现代浏览器中。它的名字来源于法语单词 "vite",意思是 "快速"。
Vite 的主要特点包括:
- 快速的冷启动:利用浏览器原生 ES 模块支持,Vite 可以在开发模式下快速启动应用。
- 按需编译:Vite 只在浏览器请求时编译文件,而不是一次性编译整个项目。
- 内置开发服务器:Vite 提供了一个内置的开发服务器,支持热模块替换(HMR)。
- 多框架支持:虽然 Vite 最初是为 Vue.js 设计的,但它也支持 React、Preact、Svelte 等框架。
2. 安装 Vite
要使用 Vite,首先需要安装 Node.js(建议使用最新稳定版)。然后可以通过 npm 或 yarn 来安装 Vite。
# 使用 npm
npm install -g create-vite
# 使用 yarn
yarn global add create-vite
3. 创建一个 Vite 项目
安装完成后,可以使用 create-vite
命令来创建一个新的 Vite 项目。
npm create vite@latest my-vite-app
yarn create vite my-vite-app
在创建项目时,Vite 会提示你选择一个模板(如 Vue、React、Svelte 等)。选择你喜欢的框架后,Vite 会自动生成项目结构。
4. 项目结构
一个典型的 Vite 项目结构如下:
my-vite-app/
├── node_modules/
├── public/
│ └── favicon.ico
├── src/
│ ├── assets/
│ ├── components/
│ ├── App.vue
│ └── main.js
├── index.html
├── package.json
├── vite.config.js
└── README.md
- public/ :存放静态资源文件,如 favicon.ico。
- src/ :项目的源代码目录。
- index.html:项目的入口 HTML 文件。
- vite.config.js:Vite 的配置文件。
5. Vite 配置文件
Vite 的配置文件 vite.config.js
允许你自定义构建行为。以下是一个简单的配置示例:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true,
},
build: {
outDir: 'dist',
assetsDir: 'assets',
},
});
- plugins:配置 Vite 插件,如 Vue 插件。
- server:配置开发服务器,如端口号和自动打开浏览器。
- build:配置生产构建,如输出目录和静态资源目录。
6. 使用插件
Vite 支持丰富的插件生态系统。你可以通过安装和配置插件来扩展 Vite 的功能。例如,要使用 Vue 插件,可以安装 `@vitejs/plugin-
# 使用 npm
npm install @vitejs/plugin-vue --save-dev
# 使用 yarn
yarn add @vitejs/plugin-vue --dev
然后在 vite.config.js
中配置插件:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
});
7. 使用 TypeScript
Vite 支持 TypeScript。要使用 TypeScript,只需在项目中安装 typescript
npm install typescript -D
创建tsconfig.json
,添加必要的配置项,
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"isolatedModules": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx"]
}
在使用 Vite 和 TypeScript 时,配置路径别名(如 @
指向 src
目录)可以通过 vite-tsconfig-paths
插件来简化
1.安装依赖
npm install vite-tsconfig-paths --save-dev
2.配置 vite.config.ts
在 vite.config.ts
文件中引入并配置 vite-tsconfig-paths
插件:
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
plugins: [tsconfigPaths()],
});
3.配置tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
4.安装 @types/node
由于 TypeScript 不直接支持 Node.js 的 path
模块,需要安装 @types/node
依赖:
npm install @types/node --save-dev
5.使用
现在可以在项目中使用路径别名了,例如:
import MyComponent from '@/components/xxx.vue';
8. 使用 CSS 预处理器
Vite 支持多种 CSS 预处理器,如 Sass、Less 和 Stylus。要使用 Sass,只需安装 sass
:
//安装sass或者less
npm install -D sass
npm install -D less
文件中使用
<template>
<div class="example">Hello, Vite!</div>
</template>
<style lang="less">
.example {
color: #3eaf7c;
background-color: #f0f0f0;
}
</style>
文件中引用
<style lang="less">
@import url("@/style/base.less");
</style>
使用 PostCSS 插件
npm install -D postcss-nesting\
然后在 postcss.config.js
中配置插件:
module.exports = {
plugins: {
'postcss-nesting': {}
}
};
9. 使用环境变量
在Vite项目中使用环境变量是一项重要的功能,可以帮助开发者根据不同的运行模式(如开发模式、生产模式等)配置不同的参数。以下将详细说明如何在Vite中配置和使用环境变量:
-
环境变量文件的创建与命名 在Vite项目中,通常会使用
.env
系列文件来管理环境变量。这些文件包括:.env
: 包含所有通用的环境变量。.env.[mode]
: 按模式划分的环境变量文件,例如.env.development
和.env.production
分别用于开发和生产环境。.env.[mode].local
: 在特定模式下加载的本地环境变量文件,例如.env.development.local
。
环境变量文件中的变量名需要以
VITE_
为前缀,这样Vite才能正确识别并加载这些变量到import.meta.env
对象中。 -
在代码中访问环境变量 在Vite项目中,可以通过
import.meta.env
对象访问环境变量。例如:
VITE_API_URL=https://api.example.com
console.log('当前环境:', import.meta.env);
console.log('API URL:', import.meta.env.VITE_API_URL);
这种方式适用于浏览器端代码,因为Vite运行在浏览器环境中。
- 在Vite配置文件中使用环境变量 在
vite.config.ts
中,可以使用loadEnv
方法加载环境变量。例如:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
define: {
'process.env': process.env
}
});
这样可以在配置文件中直接引用环境变量。
-
动态环境变量的处理 如果需要动态加载环境变量,可以借助插件或自定义逻辑。例如,通过
vite-plugin-dynamic-env
插件,可以实现动态注入环境变量。 -
环境变量的优先级与覆盖规则 Vite中的环境变量遵循以下优先级规则:
- 运行时已存在的环境变量优先级最高。
.env.[mode].local
文件优先级高于.env.[mode]
文件。.env.[mode]
文件优先级高于通用的.env
文件。
-
HTML模板中的环境变量 在HTML模板中,可以使用特殊语法
%VITE_VARIABLE%
来引用环境变量。例如:
<title>%VITE_APP_TITLE%</title>
这些变量会被Vite在构建时替换为实际值。
-
注意事项
- 环境变量文件应存储在项目根目录下,否则可能无法生效。
- 环境变量文件中的敏感信息不应提交到版本控制系统中,建议使用
.env.*.local
文件存储。 - 动态键形式的环境变量(如
VITE_API_URL_NAME
)在Vite中不支持,需使用静态键形式。
10.使用eslint 和pritter
Vite 项目中可以使用 ESLint 和 Prettier 进行代码规范和格式化管理。以下是详细的配置方法和步骤:
1. 安装依赖
需要安装 ESLint、Prettier 及其相关插件:
- 安装 ESLint 和 Vue 插件:
npm install eslint eslint-plugin-vue --save-dev
- 安装 Prettier:
npm install prettier --save-dev
- 安装 ESLint 和 Prettier 的冲突解决插件
eslint-config-prettier
:
npm install eslint-config-prettier eslint-plugin-prettier --save-dev
2. 配置 ESLint
在项目根目录下创建 .eslintrc.js
文件,并添加以下内容:
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/recommended',
'plugin:prettier/recommended',
],
parserOptions: {
parser: '@typescript-eslint/parser',
},
rules: {
'no-undef': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'prettier/prettier': ['error', { singleQuote: true, semi: false }],
},
};
上述配置中,eslint-config-prettier
和 eslint-plugin-prettier
被用来解决 ESLint 和 Prettier 的冲突,确保两者不会同时对代码进行格式化操作。
3. 配置 Prettier
在项目根目录下创建 .prettierrc
文件,并添加以下内容:
{
"semi": false,
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"endOfLine": "auto"
}
该配置文件定义了 Prettier 的格式化规则,例如禁用分号、使用单引号、设置制表符宽度等。
4. 集成到 Vite
在 vite.config.js
文件中引入 ESLint 插件:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import eslintPlugin from 'vite-plugin-eslint';
export default defineConfig({
plugins: [
vue(),
eslintPlugin({
lintOnStart: true, // 开启在启动时检查
cache: true, // 缓存检查结果以提高性能
}),
],
});
5. 集成到 VSCode
为了在 VSCode 中自动格式化代码,可以在 settings.json
文件中添加以下配置:
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
11. 使用多页面应用
Vite 支持多页面应用(MPA)。你可以在 vite.config.js
中配置多个入口点:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
main: './index.html',
about: './about.html',
},
},
},
});
12. 使用自定义路径别名
Vite 支持自定义路径别名。你可以在 vite.config.js
中配置别名:
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
});
然后在代码中使用别名:
import MyComponent from '@/components/MyComponent.vue';
13. 使用代理
Vite 支持配置代理服务器,用于解决跨域问题。你可以在 vite.config.js
中配置代理:
import { defineConfig } from 'vite';
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, ''),
},
},
},
});
14. 使用 Worker
Vite 支持 Web Workers。你可以直接在 JavaScript 中导入 Worker 文件:
import MyWorker from './worker.js?worker';
const worker = new MyWorker();
worker.postMessage('Hello, worker!');
15 使用 PWA
Vite 支持渐进式 Web 应用(PWA)。你可以使用 vite-plugin-pwa
插件来实现 PWA 功能:
# 使用 npm
npm install vite-plugin-pwa --save-dev
# 使用 yarn
yarn add vite-plugin-pwa --dev
然后在 vite.config.js
中配置插件:
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
manifest: {
name: 'My Vite App',
short_name: 'ViteApp',
theme_color: '#ffffff',
icons: [
{
src: '/icons/icon-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: '/icons/icon-512x512.png',
sizes: '512x512',
type: 'image/png',
},
],
},
}),
],
});
16. glob-import 批量导入
在 Vite 项目中,import.meta.glob
和 import.meta.globEager
提供了强大的批量导入功能,可以简化多模块项目的文件导入过程。以下是详细的使用方法和注意事项:
基本用法
- 异步导入 (
import.meta.glob
)
- 通过
import.meta.glob
方法,传入一个匹配模式(如'./glob/*'
),返回一个对象,其中键是文件路径,值是动态导入函数。
const module = import.meta.glob('./glob/*')
Object.entries(module).forEach(([key, value]) => {
value().then((res) => {
console.log(res) // 可以查看到里面对应的内容
})
})
- 该方法适用于按需加载的场景,可以减少初始加载时间。
- 同步导入 (
import.meta.globEager
)
通过 import.meta.globEager
方法,传入一个匹配模式(如 './glob/*'
),返回一个对象,其中键是文件路径,值是模块内容。
const moduleEager = import.meta.glob('./glob/*', { eager: true })
console.log(Object.entries(moduleEager))
- 该方法适用于模块较少且希望立即加载的情况,避免了异步加载的不便。
使用场景
- 批量导入组件
在 Vue 项目中,可以使用 import.meta.glob
或 import.meta.globEager
批量导入组件,并注册到 Vue 实例中。
const modules = import.meta.glob(`./*.vue`, { eager: true })
const map = {}
for (let key in modules) {
const name = 'y-' + getKebabCase(key.split('/')[1].split('.')[0])
map[name] = modules[key].default
}
export default map
- 批量导入路由模块
- 在路由管理中,可以使用
import.meta.glob
批量导入路由模块,实现模块化的路由管理。
const dynamicViewsModules = import.meta.glob('../../views/**/*.{vue,tsx}')
const keys = Object.keys(dynamicViewsModules)
const matchKeys = keys.filter((key) => {
const k = key.replace('../../views', '')
return k.startsWith(`${component}`) || k.startsWith(`/${component}`)
})
- 批量导入图片
- 在项目中,可以使用
import.meta.globEager
批量导入图片资源,并在页面中使用。
const modules = import.meta.globEager('/static/images/left-image/*.*')
const imageList = Object.values(modules).map(module => module.default)
17. 总结
Vite 是一个功能强大且灵活的构建工具,特别适合现代前端开发。它通过利用浏览器原生 ES 模块支持,提供了极快的开发体验。无论是单页面应用还是多页面应用,Vite 都能轻松应对。通过丰富的插件生态系统,你可以扩展 Vite 的功能,满足各种开发需求。