@roots/bud-imagemin
@roots/bud-imagemin optimizes image filesizes. It works with no configuration beyond installing it but also has a robust customization API.
The extension uses sharp.
Installation​
- npm
- Yarn
- pnpm
npm install @roots/bud-imagemin --save-dev
yarn add @roots/bud-imagemin --dev
pnpm add @roots/bud-imagemin --save-dev
Usage​
Once installed, all compatible assets will be run through the image minimizer. No further configuration is required.
@roots/bud-imagemin works out of the box with no configuration. It uses the sharp library to optimize images, and sticks to the default options provided by sharp.
This extension is a relatively thin wrapper around the webpack-contrib/image-minimizer-webpack-plugin. Refer to the plugin documentation for more information on how to configure it.
Manipulating images with URL parameters​
Convert to webp
​
You can convert an asset to webp
format using the ?as=webp
url parameter.
It works in both styles and scripts:
body {
background-image: url(./images/image.jpg?as=webp);
}
import image from './images/image.jpg?as=webp'
Adding additional presets​
In addition to the preconfigured ?as=webp
parameter, you may define additional generators using bud.imagemin.addPreset.
For example, this custom generator will convert an asset to png
at 80% quality when ?as=png
is appended to an image asset path.
export default async bud => {
bud.imagemin.sharp.setGenerator(`png`, {
options: {
encodeOptions: {
quality: 80,
}
},
})
}
The preset label does not necessarily need to match one of the sharp encoder keys. For example, you might want to set up something a little more persnickity like:
export default async bud => {
bud.imagemin.addPreset(`webp@50`, {
options: {
encodeOptions: {
webp: {
quality: 50
},
},
},
})
}
Set dimensions​
You can set an explicit width for an image with the ?width=n
url parameter. Likewise, you can set an explicit height with ?height=n
.
It works in both styles and scripts:
body {
background-image: url(./images/image.jpg?width=500&height=500);
}
import image from './images/image.jpg?width=500&height=500'
Setting encoder options​
You may wish to customize the encoder settings. This is done with bud.imagemin.encode.
export default async bud => {
bud.imagemin.encode(`jpeg`, {quality: 50})
bud.imagemin.encode(`svg`, {multipass: false})
}
Enable lossless compression​
export default async bud => {
bud.imagemin.lossless()
}