Installations
npm install responsive-loader
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>= 12.22.1
Node Version
14.18.1
NPM Version
6.14.15
Score
81.4
Supply Chain
69.1
Quality
77.3
Maintenance
100
Vulnerability
99.6
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (65%)
JavaScript (35%)
Developer
dazuaz
Download Statistics
Total Downloads
6,702,640
Last Day
2,837
Last Week
13,765
Last Month
60,945
Last Year
869,812
GitHub Statistics
649 Stars
236 Commits
75 Forks
10 Watching
4 Branches
16 Contributors
Bundle Size
231.83 kB
Minified
66.16 kB
Minified + Gzipped
Package Meta Information
Latest Version
3.1.2
Package Id
responsive-loader@3.1.2
Unpacked Size
49.38 kB
Size
13.93 kB
File Count
15
NPM Version
6.14.15
Node Version
14.18.1
Total Downloads
Cumulative downloads
Total Downloads
6,702,640
Last day
-23.1%
2,837
Compared to previous day
Last week
-16.9%
13,765
Compared to previous week
Last month
9.6%
60,945
Compared to previous month
Last year
-17.1%
869,812
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
1
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. Browser support is pretty good.
Install
With sharp
npm install responsive-loader sharp --save-dev
For super-charged performance and webp and avif formats support, responsive-loader works with sharp. It's recommended to use sharp if you have lots of images to transform.
1module.exports = { 2 // ... 3 module: { 4 rules: [ 5 { 6 test: /\.(png|jpe?g)$/, 7 use: [ 8 { 9 loader: 'responsive-loader', 10 options: { 11 // Set options for all transforms 12 }, 13 }, 14 ], 15 type: 'javascript/auto', 16 }, 17 ], 18 }, 19}
With jimp
npm install responsive-loader jimp --save-dev
Responsive-loader can be use with jimp to 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.
If you want to use jimp, you need to configure responsive-loader to use its adapter:
1module.exports = { 2 // ... 3 module: { 4 rules: [ 5 { 6 test: /\.(png|jpe?g)$/, 7 use: [ 8 { 9 loader: 'responsive-loader', 10 options: { 11+ adapter: require('responsive-loader/jimp') 12 }, 13 }, 14 ], 15 type: 'javascript/auto', 16 } 17 ] 18 }, 19}
Typescript
1//declare a module to your type definitions files *.d.ts 2interface ResponsiveImageOutput { 3 src: string 4 srcSet: string 5 placeholder: string | undefined 6 images: { path: string; width: number; height: number }[] 7 width: number 8 height: number 9 toString: () => string 10} 11 12declare module '*!rl' { 13 const src: ResponsiveImageOutput 14 export default src 15}
import responsiveImage from 'img/myImage.jpg?sizes[]=300,sizes[]=600,sizes[]=1024,sizes[]=2048!rl';
import responsiveImageWebp from 'img/myImage.jpg?sizes[]=300,sizes[]=600,sizes[]=1024,sizes[]=2048&format=webp!rl';
...
Then import images in your JavaScript files:
1import responsiveImage from 'img/myImage.jpg?sizes[]=300,sizes[]=600,sizes[]=1024,sizes[]=2048'; 2import responsiveImageWebp from 'img/myImage.jpg?sizes[]=300,sizes[]=600,sizes[]=1024,sizes[]=2048&format=webp'; 3 4// Outputs 5// responsiveImage.srcSet => '2fefae46cb857bc750fa5e5eed4a0cde-300.jpg 300w,2fefae46cb857bc750fa5e5eed4a0cde-600.jpg 600w,2fefae46cb857bc750fa5e5eed4a0cde-600.jpg 600w ...' 6// responsiveImage.images => [{height: 150, path: '2fefae46cb857bc750fa5e5eed4a0cde-300.jpg', width: 300}, {height: 300, path: '2fefae46cb857bc750fa5e5eed4a0cde-600.jpg', width: 600} ...] 7// responsiveImage.src => '2fefae46cb857bc750fa5e5eed4a0cde-2048.jpg' 8// responsiveImage.toString() => '2fefae46cb857bc750fa5e5eed4a0cde-2048.jpg' 9... 10 <picture> 11 <source srcSet={responsiveImageWebp.srcSet} type='image/webp' sizes='(min-width: 1024px) 1024px, 100vw'/> 12 <img 13 src={responsiveImage.src} 14 srcSet={responsiveImage.srcSet} 15 width={responsiveImage.width} 16 height={responsiveImage.height} 17 sizes='(min-width: 1024px) 1024px, 100vw' 18 loading="lazy" 19 /> 20 </picture> 21...
Notes:
width
andheight
are intrinsic and are used to avoid layout shift, other techniques involve the use of aspect ratio and padding.sizes
, without sizes, the browser assumes the image is always 100vw for any viewport.- A helpful tool to determine proper sizes https://ausi.github.io/respimagelint/
loading
do not add loading lazy if the image is part of the initial rendering of the page or close to it.srcset
Modern browsers will choose the closest best image depending on the pixel density of your screen.- in the example above is your pixel density is
>1x
for a screen>1024px
it will display the 2048 image.
- in the example above is your pixel density is
Or use it in CSS (only the first resized image will be used, if you use multiple sizes
):
1.myImage { 2 background: url('myImage.jpg?size=1140'); 3} 4 5@media (max-width: 480px) { 6 .myImage { 7 background: url('myImage.jpg?size=480'); 8 } 9}
1// Outputs placeholder image as a data URI, and three images with 100, 200, and 300px widths 2const responsiveImage = require('myImage.jpg?placeholder=true&sizes[]=100,sizes[]=200,sizes[]=300') 3 4// responsiveImage.placeholder => 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAIBAQE…' 5ReactDOM.render( 6 <div 7 style={{ 8 height: responsiveImage.height, 9 width: responsiveImage.width, 10 backgroundSize: 'cover', 11 backgroundImage: 'url("' + responsiveImage.placeholder + '")', 12 }}> 13 <img src={responsiveImage.src} srcSet={responsiveImage.srcSet} /> 14 </div>, 15 el 16)
You can also use JSON5 notation:
<source srcSet={require('./image.jpg?{sizes:[50,100,200,300,400,500,600,700,800], format: "webp"}').srcSet} type='image/webp'/>
Options
Option | Type | Default | Description |
---|---|---|---|
name | string | [hash]-[width].[ext] | Filename template for output files. |
outputPath | string | Function | undefined | Configure a custom output path for your file |
publicPath | string | Function | undefined | Configure a custom public path for your file. |
context | string | this.options.context | Custom file context, defaults to webpack.config.js context |
sizes | array | original size | Specify 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 sizes array in the loader options in your webpack.config.js . |
size | integer | original size | Specify 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) |
min | integer | As an alternative to manually specifying sizes , you can specify min , max and steps , and the sizes will be generated for you. | |
max | integer | See min above | |
steps | integer | 4 | Configure the number of images generated between min and max (inclusive) |
quality | integer | 85 | JPEG and WEBP compression quality |
format | string | original format | Either png or jpg ; use to convert to another format. webp and avif is also supported, but only by the sharp adapter |
placeholder | boolean | false | A true or false value to specify wether to output a placeholder image as a data URI |
placeholderSize | integer | 40 | A number value specifying the width of the placeholder image, if enabled with the option above |
adapter | Adapter | JIMP | Specify which adapter to use. Can only be specified in the loader options. |
disable | boolean | false | Disable processing of images by this loader (useful in development). srcSet and other attributes will still be generated but only for the original size. Note that the width and height attributes will both be set to 100 but the image will retain its original dimensions. |
esModule | boolean | false | Use ES modules syntax. |
emitFile | boolean | true | If true , emits a file (writes a file to the filesystem). If false , the loader will still return a object with the public URI but will not emit the file. It is often useful to disable this option for server-side packages. |
cacheDirectory | string or boolean | false | Experimental: If true , this will cache the result object but not the image files. The images are only produced once, when they are not found in the results object cache, or when the options change (cache key). For Development you can set query parameter to ?cacheDirectory=false . |
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
or%23FFFFFF
for webpack > 5format: webp
— Conversion to theimage/webp
format. Recognizes thequality
option.format: avif
— Conversion to theimage/avif
format. Recognizes thequality
option.progressive: boolean
- Use progressive (interlace) scan forimage/jpeg
format.rotate: number
- Rotates image more here
Examples
Set a default sizes
array, so you don't have to declare them with each require
.
1module.exports = { 2 entry: {...}, 3 output: {...}, 4 module: { 5 rules: [ 6 { 7 test: /\.(jpe?g|png|webp)$/i, 8 use: [ 9 { 10 loader: "responsive-loader", 11 options: { 12 adapter: require('responsive-loader/sharp'), 13 sizes: [320, 640, 960, 1200, 1800, 2400], 14 placeholder: true, 15 placeholderSize: 20 16 }, 17 }, 18 ], 19 } 20 ] 21 }, 22}
cacheDirectory
Type: Boolean
or string
Default: false
Experimental: If true
, this will cache the result object but not the image files. The images are only produced once, when they are not found in the results object cache, or when the options change (cache key). For Development you can set query parameter to individual images by using ?cacheDirectory=false
.
Default cache directory might be .node_modules/.cache/responsive-loader
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.(jpe?g|png)$/i, 6 use: [ 7 { 8 loader: 'responsive-loader', 9 options: { 10 esModule: true, 11 cacheDirectory: true, 12 publicPath: '/_next', 13 name: 'static/media/[name]-[hash:7]-[width].[ext]', 14 }, 15 }, 16 ], 17 }, 18 ], 19 }, 20}
esModule
Type: Boolean
Default: false
By default, responsive-loader
generates JS modules that use the CommonJS syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a ES module syntax using:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.(jpe?g|png)$/i, 6 use: [ 7 { 8 loader: 'responsive-loader', 9 options: { 10 esModule: true, 11 }, 12 }, 13 ], 14 }, 15 ], 16 }, 17}
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:
1type Adapter = (imagePath: string) => { 2 metadata: () => Promise<{width: number, height: number}> 3 resize: (config: {width: number, mime: string, options: Object}) => Promise<{data: Buffer, width: number, height: number}> 4}
The resize
method takes a single argument which has a width
, mime
and options
property (which receives all loader options)
In your webpack config, require your adapter
1{ 2 test: /\.(jpe?g|png)$/i, 3 loader: 'responsive-loader', 4 options: { 5 adapter: require('./my-adapter') 6 foo: 'bar' // will get passed to adapter.resize({width, mime, options: {foo: 'bar}}) 7 } 8}
Notes
- Doesn't support
1x
,2x
sizes, but you probably don't need it.
Usage Examples
Next.js
Pug
- How to use responsive-loader with Pug. Thanks to the awesome pug-loader.
Please submit your own example to add here
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: BSD 3-Clause "New" or "Revised" License: LICENSE:0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29
- Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
- Info: no jobLevel write permissions found
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 0 commits out of 6 are checked with a SAST tool
Reason
Found 1/25 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/dazuaz/responsive-loader/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/dazuaz/responsive-loader/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:56: update your workflow using https://app.stepsecurity.io/secureworkflow/dazuaz/responsive-loader/codeql-analysis.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:70: update your workflow using https://app.stepsecurity.io/secureworkflow/dazuaz/responsive-loader/codeql-analysis.yml/master?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
10 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-x565-32qp-m3vf
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-54xq-cgqr-rpm3
- Warn: Project is vulnerable to: GHSA-4vvj-4cpr-p986
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-776f-qx25-q3cc
Score
3.8
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More