vite常用配置
环境变量配置
.env # 所有情况下都会加载
.env.local # 所有情况下都会加载,但会被 git 忽略
.env.[mode] # 只在指定模式下加载
.env.[mode].local # 只在指定模式下加载,但会被 git 忽略
- loadEnv方法,来加载环境变量文件的配置 (.env)
- 为了防止意外地将一些环境变量泄漏到客户端, 默认情况下只有前缀为
VITE_会被加载
- 为了防止意外地将一些环境变量泄漏到客户端, 默认情况下只有前缀为
- vite解析时变量时会返回一个字符串
- 可通过envPrefix选项来自定义变量的前缀,默认是
VIEW_
定义全局变量
- 可通过define配置项,来定义全局变量
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify('v1.0.0'),
__API_URL__: 'window.__backend_api_url',
__GLOBAL_CONFIG__:{
app_id:'xxx'
}
},
})
- 定义类型提示
# global.d.ts
declare global {
const __GLOBAL_CONFIG__: {
app_id: string;
};
const __APP_VERSION__: string
}
# vite-env.d.ts
declare const __APP_VERSION__: string
optimizeDeps
依赖预构建配置,
Vite会根据应用入口(entries)自动搜集依赖,然后进行预构建依赖预构建仅适用于开发模式
-
include
-
默认情况下,不在
node_modules中的,链接的包不会被预构建。使用此选项可强制预构建链接的包 -
可以指定一些包,来强制进行预构建
-
什么情况需要手动指定预构建的包?
-
动态import
- 在某些动态
import的场景下,由于Vite按需加载的特性,经常会导致某些依赖只能在运行时被识别出来, 当进入其他页面,vite发现存在动态import的时候,才会进行二次预构建- 无法在编译构建阶段识别
- 在某些动态
-
组件按需加载的时候
- 只有在需要时,相关的代码块才会被加载,才会进行预构建
- 切换页面的时候,增加等待时间,并且导致页面重新刷新,开发体验也不好
- 通过将组件或库添加到
optimizeDeps.include,可以在初始构建时预构建它们,从而减少运行时的加载时间
build
生产编译配置
-
reportCompressedSize
- 启用/禁用 gzip 压缩大小报告。压缩大型输出文件可能会很慢,因此禁用该功能可能会提高大型项目的构建性能
-
minify: "esbuild"
- 客户端构建默认为
'esbuild',SSR构建默认为false - 它比 terser 快 20-40 倍,压缩率只差 1%-2%
- 客户端构建默认为
-
chunkSizeWarningLimit
- 默认500 ,一般设置1500-2000就可以
- chunk 大小警告的限制(以 kbs 为单位)
- 单个模块文件超过了默认块限制,就会出现分块的提示
- 建议进行代码分块后进行动态导入可以加速页面加载速度
-
cssCodeSplit
-
默认是开启,开启了css代码拆分
- 当启用时,在异步 chunk 中导入的 CSS 将内联到异步 chunk 本身,并在其被加载时一并获取
- 如果指定了
build.lib,build.cssCodeSplit会默认为false
-
是否将整个项目中的所有 CSS 将被提取到一个 CSS 文件中
-
build: {
outDir: "dist",
minify: "esbuild",
// 禁用 gzip 压缩大小报告,可略微减少打包时间
reportCompressedSize: false,
// 规定触发警告的 chunk 大小
chunkSizeWarningLimit: 2000,
rollupOptions: {
output: {
// Static resource classification and packaging
chunkFileNames: "assets/js/[name]-[hash].js",
entryFileNames: "assets/js/[name]-[hash].js",
assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
}
}
server
- 开发服务器
- 配置代理
import { defineConfig, loadEnv } from 'vite'
export default defineConfig({}=>{
const viteEnv = loadEnv(mode, process.cwd())
const { VITE_BASE_API_URL } = viteEnv
return {
server: {
host: '0.0.0.0',
port: 8888,
open: true,
proxy: {
'/api': {
target: VITE_BASE_API_URL,
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, ''),
secure: false,
},
},
},
}
})
glob import全局导入
- Vite 支持通过特殊的
import.meta.glob函数从文件系统导入多个模块
注意glob参数配置问题
- eager
- 设置模块加载模式
- eager为true,Vite在在初始化时加载所有匹配模块
- 移除
eager: true,改为按需加载文件
- import
- 指定从模块中导入的导出内容,支持 默认导出 或 命名导出
glog参数
| 参数 | 类型 | 作用 | 默认值 | 示例 | 参考资料 |
|---|---|---|---|---|---|
pattern | string 或 string[] | 定义文件匹配模式,支持 Glob 语法。可传入数组实现多模式或排除(使用 ! 前缀) | 必填 | import.meta.glob('./components/*.vue') import.meta.glob(['./dir/*.js', '!**/bar.js']) | |
eager | boolean | 控制是否同步加载所有模块。若为 true,构建时直接打包模块并返回对象;若为 false,返回异步加载函数。 | false | import.meta.glob('./modules/*.ts', { eager: true }) | |
as | 'raw' | 'url' | 'default' | 指定模块内容的返回形式: - raw:原始文本内容 - url:文件 URL 路径 - default:模块的默认导出 | 'default' |
query | string 或 `Record<string, string | number | boolean>` | 添加查询参数到导入路径,常用于自定义插件处理或资源类型标记。 | 无 |
import | string 或 string[] | 指定导入的命名导出成员,优化 Tree Shaking。 | 无(默认导入全部) | import.meta.glob('./utils/*.js', { import: 'setup' }) import.meta.glob('./api/*.ts', { import: ['get', 'post'] }) |
常用插件配置
- unplugin-auto-import
- 按需自动导入
- unplugin-vue-components
- Vue 的按需组件自动导入
- vite-plugin-router-warn
- 移除非必要的vue-router动态路由警告: No match found for location with path
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import removeNoMatch from 'vite-plugin-router-warn'
export default defineConfig(() => {
plugins: [
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
// 生成组件的类型声明文件, 设置为false则不生成
dts: 'types/components.d.ts',
}),
]
}
unplugin-vue-components配置
- 配置组件的按需自动导入
- 可以灵活配置动态导入,自由配置组件的导入组件命名的方式
- 如驼峰、横杠
- 生成的组件的类型声明文件
配置组件的按需自动导入
- 自动按需导入组件
- 自动生成组件的类型文件
- 配置好之后,直接写组件就有类型提示了
import Components from 'unplugin-vue-components/vite';
// 自定义组件匹配
const customComponentFiles = fs.readdirSync('./src/components/core');
const customComponents = filter(customComponentFiles, (item) => startsWith(item, 'custom-'));
const customComponentsType = map(customComponents, (item) => {
return {
from: `./src/components/core/${item}`,
names: [item],
};
});
export default (): UserConfig => {
return {
plugins: [
Components({
dts: 'types/components.d.ts',
types: [
...customComponentsType,
]
}),
]
}
}
解决命名冲突问题
-
当出现这个报错警告时,has naming conflicts with other components, ignored
- 表示组件的名称冲突,一般是子目录的命令冲突
-
解决:directoryAsNamespace
设置为true
Components({
...
directoryAsNamespace: true,
})