# rollup-plugin-2webp
**Repository Path**: hola/rollup-plugin-2webp
## Basic Information
- **Project Name**: rollup-plugin-2webp
- **Description**: 基于rollup的构建插件,实现在构建阶段将png/jpg转成webp格式图片,并自动替换bundle产物中的引用,支持自主控制脚本插入。
- **Primary Language**: Unknown
- **License**: ISC
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2024-08-12
- **Last Updated**: 2024-08-26
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# rollup-plugin-2webp
> 基于rollup的构建插件,实现在构建阶段将png/jpg转成webp格式图片,并自动替换bundle产物中的引用,支持自主控制脚本插入。
## 安装
```bash
// npm
npm install git+https://gitee.web.guosen.com.cn/16104/rollup-plugin-2webp.git
// yarn
yarn add https://gitee.web.guosen.com.cn/16104/rollup-plugin-2webp.git
// pnpm
pnpm add git+https://gitee.web.guosen.com.cn/16104/rollup-plugin-2webp.git
```
## 引用
```node
import towebp from "rollup-plugin-2webp"
// rollup.config.js
export default {
input: 'src/main.js',
output: ...
plugins: [
towebp()
]
...
}
// vite.config.js
export default defineConfig(({command, code})=>{
return {
...
plugins: [
towebp()
]
}
})
```
## 构建说明
> 构建过程中自动根据`assets`及`exclude`配置扫描目录并生成webp图片,并根据图片文件生成对应的css变量名称及js变量名称。
> css变量名称规则是将构建后的文件名中非数字/英文的字符用-替换,去除文件后缀,并在前面添加--,如构建的文件```fileName```是```assets/idcard_example_1@2x.ddd2a274.png```,对应的css变量是```--assets-idcard-example-1-2x-ddd2a274```,对应的webp文件名是```assets/icon-upload.86318ba1.png.webp```
> js变量名称规则是将构建后的文件名中非数字/英文的字符用_替换,去除文件后缀,并在前面添加```WEBP_```,如构建的文件```fileName```是```assets/idcard_example_1@2x.ddd2a274.png```,对应的js变量是```WEBP_ASSETS_IDCARD_EXAMPLE_1_2X_DDD2A274```,对应的webp文件名是```assets/icon-upload.86318ba1.png.webp```
>替换引用时自动使用较小的图片文件。
> **由于项目构建输出存在复杂性,变量可能没法替换成功,如果确认属此类情况,建议关闭变量替换,由开发者自行处理图片引用(可参考开发中可采用的方案)或者使用服务端根据webp支持特性分流方案。**
### 1.注入脚本1样例
> 判断是否支持webp
1. 异步模式
```html
```
2. 同步模式
```html
```
### 2.注入脚本2样例
> css变量定义
```html
```
### 3.注入脚本3样例
> js引用图片变量定义
```html
```
> 构建过程中插件在transformIndexHtml hook中默认将以上三段脚本插入到```