vite-preload-images-plugin
Version:
A Vite plugin that automatically generates preload tags for images in your build output
104 lines (75 loc) • 2.93 kB
Markdown
# vite-preload-images-plugin
一个 Vite 插件,用于在生产构建时自动为图片生成预加载标签,提升页面加载性能。
## 功能特性
- 🚀 自动扫描指定目录中的图片文件
- 📦 在生产构建时生成预加载标签
- ⚡ 支持多种图片格式 (PNG, JPG, JPEG, GIF, WebP)
- 🎯 可配置低优先级图片目录
- 🔧 完全可配置的选项
- 📝 TypeScript 支持
## 安装
```bash
npm install vite-preload-images-plugin
```
## 使用方法
### 基本用法
```typescript
import { defineConfig } from 'vite'
import preloadImagesPlugin from 'vite-preload-images-plugin'
export default defineConfig({
plugins: [
preloadImagesPlugin()
]
})
```
### 高级配置
```typescript
import { defineConfig } from 'vite'
import preloadImagesPlugin from 'vite-preload-images-plugin'
export default defineConfig({
plugins: [
preloadImagesPlugin({
// 指定需要预加载的图片目录
preloadDirs: ['src/assets', 'src/images'],
// 指定低优先级目录(会添加 fetchpriority="low")
lowPriorityDirs: ['gif', 'backgrounds'],
// 排除特定文件
excludeFiles: ['logo.png'],
// 自定义支持的图片扩展名
imageExtensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'],
// 启用调试日志
debug: true
})
]
})
```
## 配置选项
| 选项 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `preloadDirs` | `string[]` | `['src/assets']` | 需要预加载的图片目录列表 |
| `lowPriorityDirs` | `string[]` | `['gif']` | 需要特殊处理 fetchpriority 的目录 |
| `excludeFiles` | `string[]` | `[]` | 需要排除的文件列表 |
| `imageExtensions` | `string[]` | `['png', 'jpg', 'jpeg', 'gif', 'webp']` | 支持的图片扩展名 |
| `debug` | `boolean` | `false` | 是否启用调试日志 |
## 工作原理
1. **扫描阶段**: 插件会扫描配置的目录,收集所有支持的图片文件
2. **构建阶段**: 在 Vite 生产构建时,插件会分析构建产物
3. **匹配阶段**: 将源文件路径与构建后的资源路径进行匹配
4. **生成阶段**: 为匹配的图片生成预加载标签并插入到 HTML 的 `<head>` 中
## 生成的 HTML
插件会在 HTML 的 `<head>` 标签中插入类似以下的预加载标签:
```html
<!-- Auto-generated preload tags -->
<link rel="preload" as="image" href="./assets/logo-abc123.png">
<link rel="preload" as="image" href="./assets/hero-bg-def456.jpg">
<link rel="preload" as="image" href="./assets/animation-ghi789.gif" fetchpriority="low">
```
## 注意事项
- 插件只在生产构建时生效
- 确保图片文件路径正确配置
- 建议在 `lowPriorityDirs` 中配置动画图片(如 GIF)以优化加载性能
- 使用 `debug: true` 选项可以查看详细的处理日志
## 许可证
MIT
## 贡献
欢迎提交 Issue 和 Pull Request!