PostCSS srcset plugin
Assists in auto-generating background images scaled for different viewport widths.
/* Input example */
/* Output example */ {} {} {}
Options
You can pass an options object as the first argument to the plugin. Here is an explanation of the available configuration arguments and their default values:
const options = // The name of the function to make available in the css, in case you take // offense to my default naming of it. function: 'srcset' // The function that transforms the image's URL for a given media query. // You can return a promise from here if you want to do something async. `?size=`
Demo
To run the demo, clone this repo and run npm i && npm start
.
Use With Build Tools
This plugin comes with a loader for webpack, but you can use any build tool you like.
Webpack
An example of using the built-in webpack loader:
const srcsetPlugin = moduleexpots = module: rules: test: /\.css$/ use: 'style-loader' 'css-loader' loader: 'postcss-loader' options: plugins: test: /\.$/ resourceQuery: /[?&]size/ use: 'url-loader' srcsetPluginloader
Other Build Tools
If you want to use another build tool you may have to write it yourself.
Unless you're doing something very simple, in which case you can do the image
resizing just in the plugin's transformUrl
argument.
Either way, if you're happy using the same image resize function that the
webpack loader uses, it's available for you to require
:
const resizeImage = ;const fs = var image = fs// Arguments: Image buffer, image width// Returns a promise that resolves to a buffer with the resized image
ACK
This file is inspired by (and partly copied from) the srcset-loader;
check that out if you want to use srcset
in img tags.