I want to create a hook on a collection, to create image variants (avif, webp), when an image is uploaded/updated. For that I imported the library
sharp
. This works fine in the backend, but when I open the admin panel, it shows a blank screen, because it tries to import sharp in the browser as it seems.
Is there any way to execute code from a hook only on the server, without leaking any objects to the admin panel?
My solution right now is to add this to the config:
webpack: config => {
config.externals = {
sharp: 'commonjs sharp',
}
return config
},
And then dynamically import sharp in the hook:
const sharp = await import('sharp')
Seems pretty hacky though.
hey @mauz. , there's a section in our docs about how we recommend aliasing server-only modules (like sharp). Have a look and let me know if this solves your issue.
https://payloadcms.com/docs/admin/webpack#aliasing-server-only-modulesIs there also an option for typescript? Because this right here still throws an error:
looks like a typo, missing the
s
on
mocks
in your
path.resolve
Oh... my bad - now it works, but one error is still in the logs:
cms:dev: Watchpack Error (initial scan): Error: ENOTDIR: not a directory, scandir '/app/apps/cms/src/hooks/imageGeneration.ts'
bad path?
Don't think so - the path seems to match up with my structure.
@mauz. I needed the same thing today! I personally just looped my imageSizes and added a
-webp
variant using formatOptions.
Huh that's interesting, thanks for letting me know!
Tried it out - yep, works 100% better than my homegrown solution. I just don't get why features like this are buried in the docs.
@tylandavis I think your docs need a few backlinks at relevant places or examples for common use-cases (like image-resizing).
For example, I skimmed the entire REST api docs to find something that allows me to query items, instead of getting the whole collection, but never found anything (except for id, which wasn't helpful). So I created my own custom endpoint
/bySlug/[slug]
. Later I found out, from a forum post, that you have a query language/format for that. I guess now that I know what to look for it isn't particularly hard to find, but I expected to find all information about the REST api at the
REST API
menu point (or at the very least I expected there to be a paragraph which links to the Query docs).
Thanks for the feedback @mauz. , we can definitely make some improvements to our docs regarding requests and queries.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.