responsive-loader

A webpack loader for responsive images

responsive-loader

A webpack loader for responsive images. Creates multiple images from one source image, and returns a srcset. For more information on how to use srcset, read Responsive Images: If you’re just changing resolutions, use srcset.. Browser support is pretty good.

Install

Note: starting with v1.0.0, responsive-loader is only compatible with webpack 2+. For webpack 1 support, use responsive-loader@0.7.0

With jimp

npm install responsive-loader jimp --save-dev

Per default, responsive-loader uses jimpto transform images. which needs to be installed alongside responsive-loader. Because jimp is written entirely in JavaScript and doesn't have any native dependencies it will work anywhere. The main drawback is that it's pretty slow.

With sharp

npm install responsive-loader sharp --save-dev

For super-charged performance, responsive-loader also works with sharp. It's recommended to use sharp if you have lots of images to transform.

If you want to use sharp, you need to configure responsive-loader to use its adapter:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(jpe?g|png)$/i,
        loader: 'responsive-loader',
        options: {
+         adapter: require('responsive-loader/sharp')
        }
      }
    ]
  },
}

Usage

Add a rule for loading responsive images to your webpack config:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(jpe?g|png)$/i,
        loader: 'responsive-loader',
        options: {
          // If you want to enable sharp support:
          // adapter: require('responsive-loader/sharp')
        }
      }
    ]
  },
}

Then import images in your JavaScript files:

// Outputs three images with 100, 200, and 300px widths
const responsiveImage = require('myImage.jpg?sizes[]=100,sizes[]=200,sizes[]=300');

// responsiveImage.srcSet => '2fefae46cb857bc750fa5e5eed4a0cde-100.jpg 100w,2fefae46cb857bc750fa5e5eed4a0cde-200.jpg 200w,2fefae46cb857bc750fa5e5eed4a0cde-300.jpg 300w'
// responsiveImage.images => [{height: 50, path: '2fefae46cb857bc750fa5e5eed4a0cde-100.jpg', width: 100}, {height: 100, path: '2fefae46cb857bc750fa5e5eed4a0cde-200.jpg', width: 200}, {height: 150, path: '2fefae46cb857bc750fa5e5eed4a0cde-300.jpg', width: 300}]
// responsiveImage.src => '2fefae46cb857bc750fa5e5eed4a0cde-100.jpg'
// responsiveImage.toString() => '2fefae46cb857bc750fa5e5eed4a0cde-100.jpg'
ReactDOM.render(<img srcSet={responsiveImage.srcSet} src={responsiveImage.src} />, el);

// Or you can just use it as props, `srcSet` and `src` will be set properly
ReactDOM.render(<img {...responsiveImage} />, el);

Or use it in CSS (only the first resized image will be used, if you use multiple sizes):

.myImage { background: url('myImage.jpg?size=1140'); }

@media (max-width: 480px) {
  .myImage { background: url('myImage.jpg?size=480'); }
}
// Outputs placeholder image as a data URI, and three images with 100, 200, and 300px widths
const responsiveImage = require('myImage.jpg?placeholder=true&sizes[]=100,sizes[]=200,sizes[]=300');

// responsiveImage.placeholder => 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAIBAQE…'
ReactDOM.render(
  <div style={{
    height: responsiveImage.height,
    width: responsiveImage.width,
    backgroundSize: 'cover',
    backgroundImage: 'url("' + responsiveImage.placeholder + '")'
  }}>
    <img src={responsiveImage.src} srcSet={responsiveImage.srcSet} />
  </div>, el);

Options

OptionTypeDefaultDescription
namestring[hash]-[width].[ext]Filename template for output files.
outputPath`stringFunction`undefined
publicPath`stringFunction`undefined
contextstringthis.options.contextCustom file context, defaults to webpack.config.js context
sizesarrayoriginal sizeSpecify all widths you want to use; if a specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up). You may also declare a default sizesarray in the loader options in your webpack.config.js.
sizeintegeroriginal sizeSpecify one width you want to use; if the specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up)
minintegerAs an alternative to manually specifying sizes, you can specify min, maxand steps, and the sizes will be generated for you.
maxintegerSee minabove
stepsinteger4Configure the number of images generated between minand max(inclusive)
qualityinteger85JPEG compression quality
formatstringoriginal formatEither pngor jpg; use to convert to another format
placeholderbooleanfalseA true or false value to specify wether to output a placeholder image as a data URI
placeholderSizeinteger40A number value specifying the width of the placeholder image, if enabled with the option above
adapterAdapterJIMPSpecify which adapter to use. Can only be specified in the loader options.
disablebooleanfalseDisable processing of images by this loader (useful in development). srcSetand other attributes will still be generated but only for the original size. Note that the widthand heightattributes will both be set to 100but the image will retain its original dimensions.

Adapter-specific options

jimp
  • background: number— Background fill when converting transparent to opaque images. Make sure this is a valid hex number, e.g. 0xFFFFFFFF)
sharp
  • background: string— Background fill when converting transparent to opaque images. E.g. #FFFFFF

Examples

Set a default sizesarray, so you don't have to declare them with each require.

module.exports = {
  entry: {...},
  output: {...},
  module: {
    rules: [
      {
        test: /\.(jpe?g|png)$/i,
        loader: 'responsive-loader',
        options: {
          sizes: [300, 600, 1200, 2000],
          placeholder: true,
          placeholderSize: 50
        }
      }
    ]
  },
}

Writing Your Own Adapter

Maybe you want to use another image processing library or you want to change an existing one's behavior. You can write your own adapter with the following signature:

type Adapter = (imagePath: string) => {
  metadata: () => Promise<{width: number, height: number}>
  resize: (config: {width: number, mime: string, options: Object}) => Promise<{data: Buffer, width: number, height: number}>
}

The resizemethod takes a single argument which has a width, mimeand optionsproperty (which receives all loader options)

In your webpack config, require your adapter

{
  test: /\.(jpe?g|png)$/i,
  loader: 'responsive-loader',
  options: {
    adapter: require('./my-adapter')
    foo: 'bar' // will get passed to adapter.resize({width, mime, options: {foo: 'bar}})
  }
}

Notes

  • Doesn't support 1x, 2xsizes.

See also

HomePage

https://github.com/herrstucki/responsive-loader

Repository

https+https://github.com/herrstucki/responsive-loader


上一篇:eslint-config-interactivethings
下一篇:transform-markdown-links

相关推荐

  • 还在用字体图标吗,试试svg图标吧(内附vuecli-svg-sprite-loader插件)

    前言,关于字体图标 ​相信每位前端童鞋都对字体图标不陌生,毕竟网页必然少不了用大量的图标来装饰页面效果。在很早的时候,我们一般都是用img来当作图标来使用,由于大量地使用img会造成http请求过多的...

    7 天前
  • 说说vue-cli中使用flexible和px2rem-loader

    1.下载libflexible 2.在项目中引入libflexible 一般情况在(main.js中引入libflexible) 3.设置meta标签(视情况而定) 4.安装px2r...

    1 年前
  • 详解webpack之scss和postcss-loader的配置

    本文介绍了详解webpack之scss和postcssloader的配置,分享给大家,具体如下: 开始 首先配置postcssloader 在这里postcss是为了来给浏览器内核添加私有前...

    2 年前
  • 自己撸个 vue markdown loader

    最近,当我把 vueloader 升级到 v15 后发现,自己项目中所使用的一个 vuemarkdownloader 因为兼容问题而没法用了,正当我一筹莫展的时候,无意间看到 vuepress 中使用...

    2 年前
  • 编写一个webpack loader,用于获取指定目录下的图片,返回图片URL数组

    前言 经常遇到这么一个问题。做h5项目图片资源预加载的时候,我们往往需要手动的拿到一个个图片地址存在数组里面,然后再对其遍历做预加载处理,比如这样: 本着能偷懒就偷懒的心态,我们可以编写一个...

    7 个月前
  • 给 React 组件自动加上 react-hot-loader

    在 React 项目中使用 Webpack HMR 时,通常会使用 reacthotloader(/go/?target=https%3A%2F%2Fgithub.com%2Fgaearon%2Fre...

    10 个月前
  • 用 svg-sprite-loader 引入 SVG 以及它的“坑”

    在页面中以 symbol 引用的方式使用 SVG,已经成为目前最完美的图标解决方案。除了使用一些无版权图标网站如 Iconfont 提供的引入方式外,我们还可以在项目中使用 Webpack 来引入自己...

    1 个月前
  • 深入webpack打包原理,loader和plugin的实现

    本文讨论的核心内容如下: webpack进行打包的基本原理 如何自己实现一个loader和plugin 注: 本文使用的webpack版本是v4.43.0, webpackcli版本是v3.3.1...

    22 天前
  • 手把手教你写一个 Loader

    本文示例源代码请戳github博客(https://github.com/xiangxingchen/blog/tree/master/src/webpack/demo06),建议大家动手敲敲代码。

    1 年前
  • 在vue项目中使用webuploader实现文件上传

    简介: WebUploader是由团队开发的一个简单的以,的现代。在现代的浏览器里面能充分发挥HTML5的优势,同时又,沿用原来的FLASH运行时,。两套运行时,同样的调用方式,可供用户任意选用。

    10 个月前

官方社区

扫码加入 JavaScript 社区