payload-webp
payloadcms/payload plugin for automatic image conversion to webp format.
Getting started
- Add
sharp
to resolutions
field in package.json
to prevent versions mismatch*:
"resolutions": {
"sharp": "latest"
}
*PayloadCMS' sharp dependency version is often behind. This is a problem since sharp does not work with multiple versions in a single project and old versions are also a security risk. Solution is setting the wanted sharp version in resolutions
field.
-
Install the package with
npm i payload-webp
OR yarn add payload-webp
-
Import the plugin to your payload.config.ts
:
import webp from "payload-webp";
import { defaultResizeFactory } from "payload-webp";
export default buildConfig({
...
plugins: [
webp(webpPluginOptions)
]
)};
- After uploading images to your upload-enabled collection new field called webp is added with converted image => webp file meteadata and its sizes.
Access webp field with graphql like so:
query {
allMedia {
docs {
url
filesize
webp {
url
filesize
sizes {
thumbnail {
width
height
url
}
}
}
}
}
}
By default webp images are being processed to reduce their filesize as well.
Plugin options
Optionally you can pass JSON with following plugin options to tweak compression or limit conversion to particular mimeTypes or specific upload-enabled collections.
interface WebpPluginOptions {
resizeOptsFactory?: (imageSize: ImageSize) => {
width: number;
height: number;
options?: sharp.ResizeOptions;
};
maxResizeOpts?: { width?: number; height?: number; options?: sharp.ResizeOptions };
mimeTypes?: string[];
sharpWebpOptions?: sharp.WebpOptions;
collections?: CollectionConfig['slug'][];
sync?: boolean;
debug?: boolean;
overwrite?: boolean;
metadata?: boolean;
hooks?: {
afterConversion?: (result: ResultObject) => any;
afterStorage?: (result: ResultObject) => any;
};
}
Regenerate Webp images
You can regenerate existing images with following GraphQL mutation:
mutation {
WebpRegenerate(slug: String!, sort: String) {
currentFile
current
total
}
}
Arguments
Argument | Description |
---|
slug | Upload collection slug in camelCase |
sort | You can pass the sort parameter to set the direction in which images will be regenerated. Default: createdAt |
Fields and subsequent calls
You can use returned fields to show notify of current progress to user.
Any subsequent call while regeneration of particular collection is in the progress will not start new regeneration process, but will return current progress.
Buffer objects
You can access each buffer object of processed image in hooks
that you can set by Plugin Options. This way your adapter can store the files with external provider for an instance.