From 8590f6b5e8caf61f8cf9156354070aca59876d6c Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Thu, 20 Aug 2020 14:24:07 +0300 Subject: [PATCH 01/11] wip support of different originalPixelRatios --- example/README.md | 2 +- example/react-entry.tsx | 31 ++++---- example/webpack.config.ts | 112 +++++++++++++++++++++-------- package-lock.json | 6 ++ package.json | 1 + src/types.ts | 15 +++- src/utils/getOriginal.ts | 8 ++- src/webpack/imgproxyUrlBuilder.ts | 29 +++++--- src/webpack/loader.ts | 25 +++++-- src/webpack/loaderOptionsSchema.ts | 3 + 10 files changed, 171 insertions(+), 61 deletions(-) diff --git a/example/README.md b/example/README.md index f981602..b20b37d 100644 --- a/example/README.md +++ b/example/README.md @@ -3,5 +3,5 @@ Чтобы запустить этот пример, нужно предварительно запустить imgproxy локально на 8080 порту командой `docker run -e IMGPROXY_MAX_SRC_RESOLUTION=40 -p 8080:8080 -it darthsim/imgproxy`, -затем выполнить `npm run run-example` из корня проекта +затем выполнить `npm run dev` из корня проекта и открыть в браузере http://localhost:8081/. diff --git a/example/react-entry.tsx b/example/react-entry.tsx index bd3d2ae..41d2a1c 100644 --- a/example/react-entry.tsx +++ b/example/react-entry.tsx @@ -7,7 +7,9 @@ import { backgroundCssSmart } from '../src/utils/backgroundCss'; import '../src/utils/webpDetector' const oneImageForAllBreakpoints = require.context('./images/oneImageForAllBreakpoints'); -const differentBreakpoints = require.context('./images/differentBreakpoints'); +// const differentBreakpoints = require.context('./images/differentBreakpoints'); + +const oneImageForAllBreakpointsWithoutResize = require.context('./images/oneImageForAllBreakpoints?dontresize'); ReactDOM.render(
@@ -15,22 +17,23 @@ ReactDOM.render(

As picture tag

One image for all resolutions

+ -

Image with different breakpoints

- + {/*

Image with different breakpoints

*/} + {/**/} -

As background css

-

One image for all resolutions

-
- One image for all resolutions on background -
- -

Different breakpoints

-
- Image with different breakpoints on background -
- + {/*

As background css

*/} + {/*

One image for all resolutions

*/} + {/*
*/} + {/* One image for all resolutions on background*/} + {/*
*/} + {/**/} + {/*

Different breakpoints

*/} + {/*
*/} + {/* Image with different breakpoints on background*/} + {/*
*/} + {/**/}
, document.getElementById('app'), ); diff --git a/example/webpack.config.ts b/example/webpack.config.ts index de0be20..6d8edb9 100644 --- a/example/webpack.config.ts +++ b/example/webpack.config.ts @@ -1,5 +1,6 @@ import path from 'path'; import webpack from 'webpack'; +const ip = require('ip') import { Plugin } from '../src/webpack'; const config: webpack.Configuration = { @@ -23,42 +24,93 @@ const config: webpack.Configuration = { }, { test: /\.(jpe?g|png|gif)$/, - use: [ + oneOf: [ { - loader: path.resolve(__dirname, '../src/index.ts'), - options: { - breakpoints: [ - { - name: 'mobile', - maxWidth: 767, - }, - { - name: 'tablet', - minWidth: 768, - maxWidth: 1279, + resourceQuery: /dontresize/, + // TODO reuse + use: [ + { + loader: path.resolve(__dirname, '../src/index.ts'), + options: { + breakpoints: [ + { + name: 'mobile', + maxWidth: 767, + }, + { + name: 'tablet', + minWidth: 768, + maxWidth: 1279, + }, + { + name: 'desktop', + minWidth: 1280, + }, + ], + imgproxy: { + disable: false, + imagesHost: process.env.HOST || `http://${ip.address()}:8081`, + host: process.env.IMGPROXY_HOST || 'http://localhost:8080', + }, + // TODO использовать originalPixelRatio + shouldResize: false, + // originalPixelRatio: '1x', }, - { - name: 'desktop', - minWidth: 1280, + }, + { + loader: 'file-loader', + options: { + publicPath: '/build', + name: + process.env.NODE_ENV === 'development' + ? '[path][name].[ext]' + : '[path][name]-[hash:8].[ext]', + esModule: false, }, - ], - imgproxy: { - disable: false, - imagesHost: process.env.HOST || 'http://192.168.1.134:8081', - host: process.env.IMGPROXY_HOST || 'http://localhost:8080', }, - }, + ], }, { - loader: 'file-loader', - options: { - publicPath: '/build', - name: - process.env.NODE_ENV === 'development' - ? '[path][name].[ext]' - : '[path][name]-[hash:8].[ext]', - esModule: false, - }, + use: [ + { + loader: path.resolve(__dirname, '../src/index.ts'), + options: { + breakpoints: [ + { + name: 'mobile', + maxWidth: 767, + }, + { + name: 'tablet', + minWidth: 768, + maxWidth: 1279, + }, + { + name: 'desktop', + minWidth: 1280, + }, + ], + imgproxy: { + disable: false, + imagesHost: process.env.HOST || `http://${ip.address()}:8081`, + host: process.env.IMGPROXY_HOST || 'http://localhost:8080', + }, + shouldResize: true, + // originalPixelRatio: '3x', + }, + }, + { + loader: 'file-loader', + options: { + publicPath: '/build', + name: + process.env.NODE_ENV === 'development' + ? '[path][name].[ext]' + : '[path][name]-[hash:8].[ext]', + esModule: false, + }, + }, + ] }, ], }, diff --git a/package-lock.json b/package-lock.json index 2029d38..b0a8395 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4529,6 +4529,12 @@ "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==", "dev": true }, + "ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", + "dev": true + }, "ip-regex": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", diff --git a/package.json b/package.json index 80e3989..0c42ed4 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "eslint-plugin-react": "^7.20.0", "file-loader": "^6.0.0", "http-server": "^0.12.3", + "ip": "^1.1.5", "jest": "^26.0.1", "loader-utils": "^2.0.0", "prettier": "^2.0.5", diff --git a/src/types.ts b/src/types.ts index 90fcd8a..70be3cd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,20 @@ export type Dpr = '1x' | '2x' | '3x'; +// TODO поправить этот тип +// export type SrcSet = { +// '1x': string; +// } | { +// '1x': string; +// '2x': string; +// } | { +// '1x': string; +// '2x': string; +// '3x': string; +// }; export type SrcSet = { - [dpr in Dpr]: string; + '1x': string; + '2x'?: string; + '3x'?: string; }; export type ExtensionSrcSet = { diff --git a/src/utils/getOriginal.ts b/src/utils/getOriginal.ts index c904e46..dd29c8d 100644 --- a/src/utils/getOriginal.ts +++ b/src/utils/getOriginal.ts @@ -1,4 +1,8 @@ import { BreakpointSource } from '../types'; -export const getOriginal = (source: BreakpointSource): string => - source.srcSets[source.srcSets.length - 1].srcSet['3x']; +export const getOriginal = (source: BreakpointSource): string => { + // TODO здесь использовалось 3x изображение + // Надо использовать самое большое по значению + // или может быть сохранять где-то original раньше + return source.srcSets[source.srcSets.length - 1].srcSet['1x'] +} diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index b93e055..12f39fb 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -1,17 +1,17 @@ import Imgproxy from 'imgproxy'; -import { SrcSet } from '../types'; +import { Dpr, SrcSet } from '../types' type ImgproxyUrlBuilderConfig = { imagesHost: string; host: string; }; -export type BuildUrlsForAllPixelRatios = (imagePath: string, extension: string) => SrcSet; +export type BuildUrlsForPixelRatios = (pixelRatios: Dpr[], imagePath: string, extension: string) => SrcSet; export const getImgproxyUrlBuilder = ({ imagesHost, host, -}: ImgproxyUrlBuilderConfig): BuildUrlsForAllPixelRatios => { +}: ImgproxyUrlBuilderConfig): BuildUrlsForPixelRatios => { const imgproxy = new Imgproxy({ baseUrl: host, encode: false, @@ -24,10 +24,21 @@ export const getImgproxyUrlBuilder = ({ .generateUrl(imagesHost + imgPath, extension); }; - return (imagePath: string, extension: string): SrcSet => ({ - '1x': buildImgproxyUrl(imagePath, 0.3333, extension), - '2x': buildImgproxyUrl(imagePath, 0.6666, extension), - // 0 здесь означает, что не будет никакого изменения размеров картинки - '3x': buildImgproxyUrl(imagePath, 0, extension), - }); + return (pixelRatios: Dpr[], imagePath: string, extension: string): SrcSet => { + // TODO выводить коэффициенты сжатия (изменения размера) из количества элементов массива + // или из значений массива + // [1x, 2x] -> {1x: 0.5, 2x: 1} + + if (pixelRatios.length === 1) { + return { + '1x': buildImgproxyUrl(imagePath, 1, extension), + } + } + return { + '1x': buildImgproxyUrl(imagePath, 0.3333, extension), + '2x': buildImgproxyUrl(imagePath, 0.6666, extension), + // 0 здесь означает, что не будет никакого изменения размеров картинки + '3x': buildImgproxyUrl(imagePath, 0, extension), + } + }; }; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index deccada..9f609e0 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -19,6 +19,7 @@ export type LoaderOptions = { imagesHost: string; host: string; }; + shouldResize: boolean; }; // Каждый импорт картинки проходит через этот лоадер и на выходе @@ -29,6 +30,10 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' }); + // TODO + // Подготовить здесь массив с pixelRatios [1x 2x 3x] [1x 2x] [1x] + // Я не уверен в каком порядке должны быть элементы массива + const breakpoints: Breakpoint[] = options.breakpoints; // Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";' @@ -66,6 +71,8 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri let webpSrcSet: SrcSet, originalExtensionSrcSet: SrcSet, data: OrderedBreakpointSource; // Отключает процессинг картинок, генерируется srcSet только для оригинального типа изображения if (options.imgproxy.disable) { + // TODO пока не смотрим disable + originalExtensionSrcSet = { '1x': outputImagePath, '2x': outputImagePath, @@ -82,9 +89,19 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri ], }; } else { - const buildUrlsForAllPixelRatios = getImgproxyUrlBuilder(options.imgproxy); - webpSrcSet = buildUrlsForAllPixelRatios(outputImagePath, 'webp'); - originalExtensionSrcSet = buildUrlsForAllPixelRatios(outputImagePath, originalExtension); + const buildUrlsForPixelRatios = getImgproxyUrlBuilder(options.imgproxy); + console.log(options.shouldResize) + if (options.shouldResize) { + // TODO убрать хардкод, вынести в опции лоадера? + // originalRatio: 3x -> 3x 2x 1x + // originalRatio: 2x -> 2x 1x + // originalRatio: 1x -> 1x + webpSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, 'webp'); + originalExtensionSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, originalExtension); + } else { + webpSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, 'webp'); + originalExtensionSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, originalExtension); + } data = { order, breakpointMedia, @@ -100,7 +117,7 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri ], }; // Добавляем ссылки на картинки через imgproxy в глобальный объект - imageUrls.push(...Object.values(webpSrcSet), ...Object.values(originalExtensionSrcSet)); + imageUrls.push(...(Object.values(webpSrcSet) as string[]), ...(Object.values(originalExtensionSrcSet) as string[])); } const result: OrderedBreakpointSource = data; diff --git a/src/webpack/loaderOptionsSchema.ts b/src/webpack/loaderOptionsSchema.ts index 94619b8..2ac210b 100644 --- a/src/webpack/loaderOptionsSchema.ts +++ b/src/webpack/loaderOptionsSchema.ts @@ -48,6 +48,9 @@ export const schema: JSONSchema7 = { }, ], }, + shouldResize: { + type: 'boolean', + } }, required: ['breakpoints', 'imgproxy'], additionalProperties: false, From 8fefff4081c2bcab17262100fd63df12d520479a Mon Sep 17 00:00:00 2001 From: Viktor Kosinov Date: Fri, 21 Aug 2020 16:39:55 +0300 Subject: [PATCH 02/11] =?UTF-8?q?COM-2479:=20-=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D0=B2=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D1=8C=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D0=B8=D0=B7=D0=BE=D0=B1?= =?UTF-8?q?=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B1=D0=B5=D0=B7?= =?UTF-8?q?=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D0=BC=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/react-entry.tsx | 38 +++++++++++++++++------------- example/webpack.config.ts | 7 ++---- src/types.ts | 19 ++++----------- src/utils/getCompressionRatio.ts | 17 +++++++++++++ src/utils/getOriginal.ts | 9 ++++--- src/utils/getPixelRations.ts | 10 ++++++++ src/utils/index.ts | 2 ++ src/webpack/imgproxyUrlBuilder.ts | 22 ++++++----------- src/webpack/loader.ts | 27 ++++++--------------- src/webpack/loaderOptionsSchema.ts | 4 ++-- 10 files changed, 78 insertions(+), 77 deletions(-) create mode 100644 src/utils/getCompressionRatio.ts create mode 100644 src/utils/getPixelRations.ts diff --git a/example/react-entry.tsx b/example/react-entry.tsx index 41d2a1c..e4bd6d0 100644 --- a/example/react-entry.tsx +++ b/example/react-entry.tsx @@ -2,15 +2,23 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { PictureSmart } from '../src/react'; import { backgroundCssSmart } from '../src/utils/backgroundCss'; +import { getOriginal } from '../src/utils' // Adds 'webp' class to html element if the browser supports webp. import '../src/utils/webpDetector' const oneImageForAllBreakpoints = require.context('./images/oneImageForAllBreakpoints'); -// const differentBreakpoints = require.context('./images/differentBreakpoints'); +const differentBreakpoints = require.context('./images/differentBreakpoints'); const oneImageForAllBreakpointsWithoutResize = require.context('./images/oneImageForAllBreakpoints?dontresize'); +// Usage example getOriginal () +const myImageDataDontresize = require('./images/oneImageForAllBreakpoints/all.png?dontresize') +const myImageData = require('./images/oneImageForAllBreakpoints/all.png') + +console.log(getOriginal(myImageData)) +console.log(getOriginal(myImageDataDontresize)) + ReactDOM.render(

Example usage of csssr.images

@@ -19,21 +27,19 @@ ReactDOM.render(

One image for all resolutions

- {/*

Image with different breakpoints

*/} - {/**/} - - - {/*

As background css

*/} - {/*

One image for all resolutions

*/} - {/*
*/} - {/* One image for all resolutions on background*/} - {/*
*/} - {/**/} - {/*

Different breakpoints

*/} - {/*
*/} - {/* Image with different breakpoints on background*/} - {/*
*/} - {/**/} +

Image with different breakpoints

+ +

As background css

+

One image for all resolutions

+
+ One image for all resolutions on background +
+ +

Different breakpoints

+
+ Image with different breakpoints on background +
+
, document.getElementById('app'), ); diff --git a/example/webpack.config.ts b/example/webpack.config.ts index 6d8edb9..37fb4f0 100644 --- a/example/webpack.config.ts +++ b/example/webpack.config.ts @@ -52,9 +52,7 @@ const config: webpack.Configuration = { imagesHost: process.env.HOST || `http://${ip.address()}:8081`, host: process.env.IMGPROXY_HOST || 'http://localhost:8080', }, - // TODO использовать originalPixelRatio - shouldResize: false, - // originalPixelRatio: '1x', + originalPixelRatio: '1x', }, }, { @@ -95,8 +93,7 @@ const config: webpack.Configuration = { imagesHost: process.env.HOST || `http://${ip.address()}:8081`, host: process.env.IMGPROXY_HOST || 'http://localhost:8080', }, - shouldResize: true, - // originalPixelRatio: '3x', + originalPixelRatio: '3x', }, }, { diff --git a/src/types.ts b/src/types.ts index 70be3cd..fbed3d7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,20 +1,11 @@ export type Dpr = '1x' | '2x' | '3x'; -// TODO поправить этот тип -// export type SrcSet = { -// '1x': string; -// } | { -// '1x': string; -// '2x': string; -// } | { -// '1x': string; -// '2x': string; -// '3x': string; -// }; +export type CompressionRatio = { + [dpr in Dpr]?: number; +} + export type SrcSet = { - '1x': string; - '2x'?: string; - '3x'?: string; + [dpr in Dpr]?: string; }; export type ExtensionSrcSet = { diff --git a/src/utils/getCompressionRatio.ts b/src/utils/getCompressionRatio.ts new file mode 100644 index 0000000..c7f40cb --- /dev/null +++ b/src/utils/getCompressionRatio.ts @@ -0,0 +1,17 @@ +import { Dpr, CompressionRatio } from '../types' + +// [1x, 2x] -> {1x: 0.5, 2x: 0} + +export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { + const length = pixelRatios.length; + + return pixelRatios.reduce((acc: CompressionRatio, item: Dpr, index: number) => { + if (index + 1 === length) { + acc[item]= 0 + return acc + } + + acc[item] = (index + 1) / length + return acc + },{}) +} diff --git a/src/utils/getOriginal.ts b/src/utils/getOriginal.ts index dd29c8d..f30ade3 100644 --- a/src/utils/getOriginal.ts +++ b/src/utils/getOriginal.ts @@ -1,8 +1,7 @@ import { BreakpointSource } from '../types'; -export const getOriginal = (source: BreakpointSource): string => { - // TODO здесь использовалось 3x изображение - // Надо использовать самое большое по значению - // или может быть сохранять где-то original раньше - return source.srcSets[source.srcSets.length - 1].srcSet['1x'] +export const getOriginal = (source: BreakpointSource): string | undefined => { + const srcSet = source.srcSets[source.srcSets.length - 1].srcSet; + + return srcSet['3x'] || srcSet['2x'] || srcSet['1x'] } diff --git a/src/utils/getPixelRations.ts b/src/utils/getPixelRations.ts new file mode 100644 index 0000000..62e6a82 --- /dev/null +++ b/src/utils/getPixelRations.ts @@ -0,0 +1,10 @@ +import { Dpr } from '../types'; + +export const getPixelRations = (originalPixelRatio: Dpr):Dpr[] => { + switch (originalPixelRatio) { + case '1x': return ['1x'] + case '2x': return ['1x','2x'] + case '3x': return ['1x', '2x', '3x'] + default: return ['1x'] + } +} diff --git a/src/utils/index.ts b/src/utils/index.ts index ed31173..cf76eca 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -3,3 +3,5 @@ export { getBreakpointMedia } from './getBreakpointMedia'; export { getSrcSetString } from './getSrcSetString'; export { getSources } from './getSources'; export { getOriginal } from './getOriginal'; +export { getPixelRations } from './getPixelRations' +export { getCompressionRatio } from './getCompressionRatio' diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index 12f39fb..43b5f74 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -1,5 +1,6 @@ import Imgproxy from 'imgproxy'; import { Dpr, SrcSet } from '../types' +import { getCompressionRatio } from '../utils' type ImgproxyUrlBuilderConfig = { imagesHost: string; @@ -25,20 +26,11 @@ export const getImgproxyUrlBuilder = ({ }; return (pixelRatios: Dpr[], imagePath: string, extension: string): SrcSet => { - // TODO выводить коэффициенты сжатия (изменения размера) из количества элементов массива - // или из значений массива - // [1x, 2x] -> {1x: 0.5, 2x: 1} + const compressionsRatio = getCompressionRatio(pixelRatios) - if (pixelRatios.length === 1) { - return { - '1x': buildImgproxyUrl(imagePath, 1, extension), - } - } - return { - '1x': buildImgproxyUrl(imagePath, 0.3333, extension), - '2x': buildImgproxyUrl(imagePath, 0.6666, extension), - // 0 здесь означает, что не будет никакого изменения размеров картинки - '3x': buildImgproxyUrl(imagePath, 0, extension), - } - }; + return pixelRatios.reduce((acc:SrcSet, item: Dpr) => { + acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension) + return acc + },{}) + } }; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index 9f609e0..d82f046 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -3,10 +3,10 @@ import path from 'path'; import loaderUtils from 'loader-utils'; import validateOptions from 'schema-utils'; import { getImgproxyUrlBuilder } from './imgproxyUrlBuilder'; -import { Breakpoint, OrderedBreakpointSource, SrcSet } from '../types'; +import { Breakpoint, OrderedBreakpointSource, SrcSet, Dpr } from '../types'; import { imageUrls } from './plugin'; import { schema } from './loaderOptionsSchema'; -import { getBreakpointMedia } from '../utils'; +import { getBreakpointMedia, getPixelRations } from '../utils'; // Такое имя используется, если нужна одна картинка для всех разрешений // В таком случаем не будут сгенерированы медиа выражения для разных breakpoint'ов @@ -19,7 +19,7 @@ export type LoaderOptions = { imagesHost: string; host: string; }; - shouldResize: boolean; + originalPixelRatio: Dpr; }; // Каждый импорт картинки проходит через этот лоадер и на выходе @@ -30,12 +30,8 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' }); - // TODO - // Подготовить здесь массив с pixelRatios [1x 2x 3x] [1x 2x] [1x] - // Я не уверен в каком порядке должны быть элементы массива - + const pixelRations: Dpr[] = getPixelRations(options.originalPixelRatio) const breakpoints: Breakpoint[] = options.breakpoints; - // Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";' // Получаем оригинальное имя файла изображения (originalImageFileName = mobile.all.png) const originalImageFileName = path.relative(this.context, this.resourcePath); @@ -90,18 +86,9 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri }; } else { const buildUrlsForPixelRatios = getImgproxyUrlBuilder(options.imgproxy); - console.log(options.shouldResize) - if (options.shouldResize) { - // TODO убрать хардкод, вынести в опции лоадера? - // originalRatio: 3x -> 3x 2x 1x - // originalRatio: 2x -> 2x 1x - // originalRatio: 1x -> 1x - webpSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, 'webp'); - originalExtensionSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, originalExtension); - } else { - webpSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, 'webp'); - originalExtensionSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, originalExtension); - } + webpSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, 'webp'); + originalExtensionSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, originalExtension); + data = { order, breakpointMedia, diff --git a/src/webpack/loaderOptionsSchema.ts b/src/webpack/loaderOptionsSchema.ts index 2ac210b..4e62651 100644 --- a/src/webpack/loaderOptionsSchema.ts +++ b/src/webpack/loaderOptionsSchema.ts @@ -48,8 +48,8 @@ export const schema: JSONSchema7 = { }, ], }, - shouldResize: { - type: 'boolean', + originalPixelRatio: { + type: 'string' } }, required: ['breakpoints', 'imgproxy'], From 49ed84a210b61f2e5a741c2b0ed26265351a376e Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Fri, 21 Aug 2020 17:07:05 +0300 Subject: [PATCH 03/11] make types more stricter --- src/types.ts | 8 ++++++-- src/utils/getCompressionRatio.ts | 4 ++-- src/webpack/imgproxyUrlBuilder.ts | 4 ++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/types.ts b/src/types.ts index fbed3d7..aadada1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,11 +1,15 @@ export type Dpr = '1x' | '2x' | '3x'; export type CompressionRatio = { - [dpr in Dpr]?: number; + "1x": number; + "2x"?: number; + "3x"?: number; } export type SrcSet = { - [dpr in Dpr]?: string; + "1x": string; + "2x"?: string; + "3x"?: string; }; export type ExtensionSrcSet = { diff --git a/src/utils/getCompressionRatio.ts b/src/utils/getCompressionRatio.ts index c7f40cb..7af1832 100644 --- a/src/utils/getCompressionRatio.ts +++ b/src/utils/getCompressionRatio.ts @@ -5,7 +5,7 @@ import { Dpr, CompressionRatio } from '../types' export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { const length = pixelRatios.length; - return pixelRatios.reduce((acc: CompressionRatio, item: Dpr, index: number) => { + return pixelRatios.reduce((acc, item, index) => { if (index + 1 === length) { acc[item]= 0 return acc @@ -13,5 +13,5 @@ export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { acc[item] = (index + 1) / length return acc - },{}) + },{} as CompressionRatio) } diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index 43b5f74..44ad86a 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -28,9 +28,9 @@ export const getImgproxyUrlBuilder = ({ return (pixelRatios: Dpr[], imagePath: string, extension: string): SrcSet => { const compressionsRatio = getCompressionRatio(pixelRatios) - return pixelRatios.reduce((acc:SrcSet, item: Dpr) => { + return pixelRatios.reduce((acc, item) => { acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension) return acc - },{}) + }, {} as SrcSet) } }; From f2007a944c59af64bda86dcb249b59876d601867 Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Fri, 21 Aug 2020 17:54:38 +0300 Subject: [PATCH 04/11] lint, refactor, rename, add example with background --- example/react-entry.tsx | 35 ++++++-- example/webpack.config.ts | 128 +++++++++++------------------ package-lock.json | 11 ++- package.json | 1 + src/types.ts | 14 ++-- src/utils/getCompressionRatio.ts | 18 ++-- src/utils/getOriginal.ts | 4 +- src/utils/getPixelRations.ts | 16 ++-- src/utils/index.ts | 4 +- src/utils/webpDetector.ts | 16 ++-- src/webpack/imgproxyUrlBuilder.ts | 20 +++-- src/webpack/loader.ts | 20 +++-- src/webpack/loaderOptionsSchema.ts | 4 +- 13 files changed, 152 insertions(+), 139 deletions(-) diff --git a/example/react-entry.tsx b/example/react-entry.tsx index e4bd6d0..e29abb6 100644 --- a/example/react-entry.tsx +++ b/example/react-entry.tsx @@ -2,44 +2,61 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { PictureSmart } from '../src/react'; import { backgroundCssSmart } from '../src/utils/backgroundCss'; -import { getOriginal } from '../src/utils' +import { getOriginal } from '../src/utils'; // Adds 'webp' class to html element if the browser supports webp. -import '../src/utils/webpDetector' +import '../src/utils/webpDetector'; const oneImageForAllBreakpoints = require.context('./images/oneImageForAllBreakpoints'); const differentBreakpoints = require.context('./images/differentBreakpoints'); -const oneImageForAllBreakpointsWithoutResize = require.context('./images/oneImageForAllBreakpoints?dontresize'); +const imageWithoutResize = require.context('./images/oneImageForAllBreakpoints?dontresize'); -// Usage example getOriginal () -const myImageDataDontresize = require('./images/oneImageForAllBreakpoints/all.png?dontresize') -const myImageData = require('./images/oneImageForAllBreakpoints/all.png') +const myImageData = require('./images/oneImageForAllBreakpoints/all.png'); +const myImageWithoutResizeData = require('./images/oneImageForAllBreakpoints/all.png?dontresize'); -console.log(getOriginal(myImageData)) -console.log(getOriginal(myImageDataDontresize)) +// Usage example getOriginal () +console.log(getOriginal(myImageData)); +console.log(getOriginal(myImageWithoutResizeData)); ReactDOM.render(

Example usage of csssr.images

As picture tag

+

One image for all resolutions

- +

Image with different breakpoints

+ +

Image without resize

+ +

As background css

+

One image for all resolutions

One image for all resolutions on background
+

Different breakpoints

Image with different breakpoints on background
+ +

Image without resize

+ +
+ Image without resize on background +
+
, document.getElementById('app'), ); diff --git a/example/webpack.config.ts b/example/webpack.config.ts index 37fb4f0..5b96552 100644 --- a/example/webpack.config.ts +++ b/example/webpack.config.ts @@ -1,7 +1,52 @@ import path from 'path'; import webpack from 'webpack'; -const ip = require('ip') +import ip from 'ip'; import { Plugin } from '../src/webpack'; +import { Dpr } from '../src/types'; + +const handleImagesForOriginalPixelRatio = (originalPixelRatio: Dpr) => { + return { + use: [ + { + loader: path.resolve(__dirname, '../src/index.ts'), + options: { + breakpoints: [ + { + name: 'mobile', + maxWidth: 767, + }, + { + name: 'tablet', + minWidth: 768, + maxWidth: 1279, + }, + { + name: 'desktop', + minWidth: 1280, + }, + ], + imgproxy: { + disable: false, + imagesHost: process.env.HOST || `http://${ip.address()}:8081`, + host: process.env.IMGPROXY_HOST || 'http://localhost:8080', + }, + originalPixelRatio, + }, + }, + { + loader: 'file-loader', + options: { + publicPath: '/build', + name: + process.env.NODE_ENV === 'development' + ? '[path][name].[ext]' + : '[path][name]-[hash:8].[ext]', + esModule: false, + }, + }, + ], + }; +}; const config: webpack.Configuration = { mode: 'production', @@ -27,87 +72,10 @@ const config: webpack.Configuration = { oneOf: [ { resourceQuery: /dontresize/, - // TODO reuse - use: [ - { - loader: path.resolve(__dirname, '../src/index.ts'), - options: { - breakpoints: [ - { - name: 'mobile', - maxWidth: 767, - }, - { - name: 'tablet', - minWidth: 768, - maxWidth: 1279, - }, - { - name: 'desktop', - minWidth: 1280, - }, - ], - imgproxy: { - disable: false, - imagesHost: process.env.HOST || `http://${ip.address()}:8081`, - host: process.env.IMGPROXY_HOST || 'http://localhost:8080', - }, - originalPixelRatio: '1x', - }, - }, - { - loader: 'file-loader', - options: { - publicPath: '/build', - name: - process.env.NODE_ENV === 'development' - ? '[path][name].[ext]' - : '[path][name]-[hash:8].[ext]', - esModule: false, - }, - }, - ], + ...handleImagesForOriginalPixelRatio('1x'), }, { - use: [ - { - loader: path.resolve(__dirname, '../src/index.ts'), - options: { - breakpoints: [ - { - name: 'mobile', - maxWidth: 767, - }, - { - name: 'tablet', - minWidth: 768, - maxWidth: 1279, - }, - { - name: 'desktop', - minWidth: 1280, - }, - ], - imgproxy: { - disable: false, - imagesHost: process.env.HOST || `http://${ip.address()}:8081`, - host: process.env.IMGPROXY_HOST || 'http://localhost:8080', - }, - originalPixelRatio: '3x', - }, - }, - { - loader: 'file-loader', - options: { - publicPath: '/build', - name: - process.env.NODE_ENV === 'development' - ? '[path][name].[ext]' - : '[path][name]-[hash:8].[ext]', - esModule: false, - }, - }, - ] + ...handleImagesForOriginalPixelRatio('3x'), }, ], }, diff --git a/package-lock.json b/package-lock.json index b0a8395..7313107 100644 --- a/package-lock.json +++ b/package-lock.json @@ -945,6 +945,14 @@ "@types/node": "*" } }, + "@types/ip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/ip/-/ip-1.1.0.tgz", + "integrity": "sha512-dwNe8gOoF70VdL6WJBwVHtQmAX4RMd62M+mAB9HQFjG1/qiCLM/meRy95Pd14FYBbEDwCq7jgJs89cHpLBu4HQ==", + "requires": { + "@types/node": "*" + } + }, "@types/istanbul-lib-coverage": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.2.tgz", @@ -999,8 +1007,7 @@ "@types/node": { "version": "14.0.23", "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.23.tgz", - "integrity": "sha512-Z4U8yDAl5TFkmYsZdFPdjeMa57NOvnaf1tljHzhouaPEp7LCj2JKkejpI1ODviIAQuW4CcQmxkQ77rnLsOOoKw==", - "dev": true + "integrity": "sha512-Z4U8yDAl5TFkmYsZdFPdjeMa57NOvnaf1tljHzhouaPEp7LCj2JKkejpI1ODviIAQuW4CcQmxkQ77rnLsOOoKw==" }, "@types/normalize-package-data": { "version": "2.4.0", diff --git a/package.json b/package.json index 0c42ed4..4fecb9a 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "webpack-cli": "^3.3.12" }, "dependencies": { + "@types/ip": "^1.1.0", "imgproxy": "^0.1.2", "react": "^16.13.1", "react-dom": "^16.13.1" diff --git a/src/types.ts b/src/types.ts index aadada1..68b2552 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,15 +1,15 @@ export type Dpr = '1x' | '2x' | '3x'; export type CompressionRatio = { - "1x": number; - "2x"?: number; - "3x"?: number; -} + '1x': number; + '2x'?: number; + '3x'?: number; +}; export type SrcSet = { - "1x": string; - "2x"?: string; - "3x"?: string; + '1x': string; + '2x'?: string; + '3x'?: string; }; export type ExtensionSrcSet = { diff --git a/src/utils/getCompressionRatio.ts b/src/utils/getCompressionRatio.ts index 7af1832..833a3da 100644 --- a/src/utils/getCompressionRatio.ts +++ b/src/utils/getCompressionRatio.ts @@ -1,4 +1,4 @@ -import { Dpr, CompressionRatio } from '../types' +import { Dpr, CompressionRatio } from '../types'; // [1x, 2x] -> {1x: 0.5, 2x: 0} @@ -6,12 +6,12 @@ export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { const length = pixelRatios.length; return pixelRatios.reduce((acc, item, index) => { - if (index + 1 === length) { - acc[item]= 0 - return acc - } + if (index + 1 === length) { + acc[item] = 0; + return acc; + } - acc[item] = (index + 1) / length - return acc - },{} as CompressionRatio) -} + acc[item] = (index + 1) / length; + return acc; + }, {} as CompressionRatio); +}; diff --git a/src/utils/getOriginal.ts b/src/utils/getOriginal.ts index f30ade3..f30ad08 100644 --- a/src/utils/getOriginal.ts +++ b/src/utils/getOriginal.ts @@ -3,5 +3,5 @@ import { BreakpointSource } from '../types'; export const getOriginal = (source: BreakpointSource): string | undefined => { const srcSet = source.srcSets[source.srcSets.length - 1].srcSet; - return srcSet['3x'] || srcSet['2x'] || srcSet['1x'] -} + return srcSet['3x'] || srcSet['2x'] || srcSet['1x']; +}; diff --git a/src/utils/getPixelRations.ts b/src/utils/getPixelRations.ts index 62e6a82..0e7dd4f 100644 --- a/src/utils/getPixelRations.ts +++ b/src/utils/getPixelRations.ts @@ -1,10 +1,14 @@ import { Dpr } from '../types'; -export const getPixelRations = (originalPixelRatio: Dpr):Dpr[] => { +export const getPixelRations = (originalPixelRatio: Dpr): Dpr[] => { switch (originalPixelRatio) { - case '1x': return ['1x'] - case '2x': return ['1x','2x'] - case '3x': return ['1x', '2x', '3x'] - default: return ['1x'] + case '1x': + return ['1x']; + case '2x': + return ['1x', '2x']; + case '3x': + return ['1x', '2x', '3x']; + default: + return ['1x']; } -} +}; diff --git a/src/utils/index.ts b/src/utils/index.ts index cf76eca..370d82a 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -3,5 +3,5 @@ export { getBreakpointMedia } from './getBreakpointMedia'; export { getSrcSetString } from './getSrcSetString'; export { getSources } from './getSources'; export { getOriginal } from './getOriginal'; -export { getPixelRations } from './getPixelRations' -export { getCompressionRatio } from './getCompressionRatio' +export { getPixelRations } from './getPixelRations'; +export { getCompressionRatio } from './getCompressionRatio'; diff --git a/src/utils/webpDetector.ts b/src/utils/webpDetector.ts index 43282ba..6cdabe8 100644 --- a/src/utils/webpDetector.ts +++ b/src/utils/webpDetector.ts @@ -1,13 +1,15 @@ // https://stackoverflow.com/a/27232658 const canUseWebp = (): boolean => { - const canvas = document.createElement('canvas') - canvas.width = canvas.height = 1 - return Boolean(canvas.toDataURL && - canvas.toDataURL('image/webp') && - canvas.toDataURL('image/webp').indexOf('image/webp') === 5) -} + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 1; + return Boolean( + canvas.toDataURL && + canvas.toDataURL('image/webp') && + canvas.toDataURL('image/webp').indexOf('image/webp') === 5, + ); +}; if (canUseWebp()) { - document.documentElement.classList.add('webp') + document.documentElement.classList.add('webp'); } diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index 44ad86a..5c93071 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -1,13 +1,17 @@ import Imgproxy from 'imgproxy'; -import { Dpr, SrcSet } from '../types' -import { getCompressionRatio } from '../utils' +import { Dpr, SrcSet } from '../types'; +import { getCompressionRatio } from '../utils'; type ImgproxyUrlBuilderConfig = { imagesHost: string; host: string; }; -export type BuildUrlsForPixelRatios = (pixelRatios: Dpr[], imagePath: string, extension: string) => SrcSet; +export type BuildUrlsForPixelRatios = ( + pixelRatios: Dpr[], + imagePath: string, + extension: string, +) => SrcSet; export const getImgproxyUrlBuilder = ({ imagesHost, @@ -26,11 +30,11 @@ export const getImgproxyUrlBuilder = ({ }; return (pixelRatios: Dpr[], imagePath: string, extension: string): SrcSet => { - const compressionsRatio = getCompressionRatio(pixelRatios) + const compressionsRatio = getCompressionRatio(pixelRatios); return pixelRatios.reduce((acc, item) => { - acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension) - return acc - }, {} as SrcSet) - } + acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension); + return acc; + }, {} as SrcSet); + }; }; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index d82f046..e01ef4d 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -26,11 +26,11 @@ export type LoaderOptions = { // для каждой картинки получится массив с двумя значениями – // srcset'ы для webp и srcset для оригинального расширения изображения export const loader = function (this: webpack.loader.LoaderContext, source: string): string { - const options = loaderUtils.getOptions(this) as unknown as LoaderOptions; + const options = (loaderUtils.getOptions(this) as unknown) as LoaderOptions; validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' }); - const pixelRations: Dpr[] = getPixelRations(options.originalPixelRatio) + const pixelRations: Dpr[] = getPixelRations(options.originalPixelRatio); const breakpoints: Breakpoint[] = options.breakpoints; // Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";' // Получаем оригинальное имя файла изображения (originalImageFileName = mobile.all.png) @@ -62,7 +62,10 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri const breakpointMedia = breakpointName === all ? null : getBreakpointMedia(breakpoints[order]); // Получаем путь до картинки (outputImagePath = '/build/myImage/mobile.all-4b767a7b.png') - const outputImagePath = source.replace(/^module.exports = (__webpack_public_path__ \+ )?"(.+)";$/, (a, b, imagePath) => imagePath); + const outputImagePath = source.replace( + /^module.exports = (__webpack_public_path__ \+ )?"(.+)";$/, + (a, b, imagePath) => imagePath, + ); let webpSrcSet: SrcSet, originalExtensionSrcSet: SrcSet, data: OrderedBreakpointSource; // Отключает процессинг картинок, генерируется srcSet только для оригинального типа изображения @@ -87,7 +90,11 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri } else { const buildUrlsForPixelRatios = getImgproxyUrlBuilder(options.imgproxy); webpSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, 'webp'); - originalExtensionSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, originalExtension); + originalExtensionSrcSet = buildUrlsForPixelRatios( + pixelRations, + outputImagePath, + originalExtension, + ); data = { order, @@ -104,7 +111,10 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri ], }; // Добавляем ссылки на картинки через imgproxy в глобальный объект - imageUrls.push(...(Object.values(webpSrcSet) as string[]), ...(Object.values(originalExtensionSrcSet) as string[])); + imageUrls.push( + ...(Object.values(webpSrcSet) as string[]), + ...(Object.values(originalExtensionSrcSet) as string[]), + ); } const result: OrderedBreakpointSource = data; diff --git a/src/webpack/loaderOptionsSchema.ts b/src/webpack/loaderOptionsSchema.ts index 4e62651..75a554d 100644 --- a/src/webpack/loaderOptionsSchema.ts +++ b/src/webpack/loaderOptionsSchema.ts @@ -49,8 +49,8 @@ export const schema: JSONSchema7 = { ], }, originalPixelRatio: { - type: 'string' - } + type: 'string', + }, }, required: ['breakpoints', 'imgproxy'], additionalProperties: false, From 8031e58746fec4bb8fdb33aca31f28a47b11dafb Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Fri, 21 Aug 2020 17:56:26 +0300 Subject: [PATCH 05/11] fix typo --- example/react-entry.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/react-entry.tsx b/example/react-entry.tsx index e29abb6..6771479 100644 --- a/example/react-entry.tsx +++ b/example/react-entry.tsx @@ -53,7 +53,7 @@ ReactDOM.render(

Image without resize

-
+
Image without resize on background
From a0e29985f8265d98e709b964f53e1bda7047848e Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Fri, 21 Aug 2020 22:35:23 +0300 Subject: [PATCH 06/11] improve typings --- src/utils/getOriginal.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/getOriginal.ts b/src/utils/getOriginal.ts index f30ad08..de2a197 100644 --- a/src/utils/getOriginal.ts +++ b/src/utils/getOriginal.ts @@ -1,6 +1,6 @@ import { BreakpointSource } from '../types'; -export const getOriginal = (source: BreakpointSource): string | undefined => { +export const getOriginal = (source: BreakpointSource) => { const srcSet = source.srcSets[source.srcSets.length - 1].srcSet; return srcSet['3x'] || srcSet['2x'] || srcSet['1x']; From 820d213964df12dc9b2770d8102be96f660e3aee Mon Sep 17 00:00:00 2001 From: Viktor Kosinov Date: Mon, 24 Aug 2020 19:05:20 +0300 Subject: [PATCH 07/11] COM-2479: - refactoring backgroundCss, add tests - add tests getCompressionRatio - add getOriginalExtensionSrcSet, add test - refactoring dev mode - originalPixelRatio typing refactoring --- src/utils/__tests__/backgroundCss.ts | 31 +++++++++++++++++++ src/utils/__tests__/getCompressionRatio.ts | 20 ++++++++++++ .../__tests__/getOriginalExtensionSrcSet.ts | 20 ++++++++++++ src/utils/backgroundCss.ts | 10 +++--- src/utils/getCompressionRatio.ts | 2 -- src/utils/getOriginalExtensionSrcSet.ts | 8 +++++ src/utils/getPixelRations.ts | 2 -- src/utils/index.ts | 1 + src/webpack/loader.ts | 17 +++------- src/webpack/loaderOptionsSchema.ts | 3 +- 10 files changed, 92 insertions(+), 22 deletions(-) create mode 100644 src/utils/__tests__/getCompressionRatio.ts create mode 100644 src/utils/__tests__/getOriginalExtensionSrcSet.ts create mode 100644 src/utils/getOriginalExtensionSrcSet.ts diff --git a/src/utils/__tests__/backgroundCss.ts b/src/utils/__tests__/backgroundCss.ts index ca6c704..3ca4b86 100644 --- a/src/utils/__tests__/backgroundCss.ts +++ b/src/utils/__tests__/backgroundCss.ts @@ -397,3 +397,34 @@ test('backgroundCss multiple breakpoints, png and webp', () => { } }`); }); + +test('backgroundCss all breakpoints, png and webp, one pixel ratio', () => { + expect( + backgroundCss('.my-selector', [ + { + breakpointMedia: null, + srcSets: [ + { + extension: 'png', + srcSet: { + '1x': '/mobile.all.1x.png', + }, + }, + { + extension: 'webp', + srcSet: { + '1x': '/mobile.all.1x.webp', + }, + }, + ], + }, + ]), + ).toBeSameCss(` + .my-selector { + background-image: url(/mobile.all.1x.png); + } + html.webp .my-selector { + background-image: url(/mobile.all.1x.webp); + } +`); +}); diff --git a/src/utils/__tests__/getCompressionRatio.ts b/src/utils/__tests__/getCompressionRatio.ts new file mode 100644 index 0000000..b58f33b --- /dev/null +++ b/src/utils/__tests__/getCompressionRatio.ts @@ -0,0 +1,20 @@ +import { getCompressionRatio } from '../index'; + + +test('Pixel ratios 1x', () => { + expect( + getCompressionRatio(['1x']), + ).toStrictEqual({"1x": 0}); +}); + +test('Pixel ratios 1x, 2x', () => { + expect( + getCompressionRatio(['1x','2x']), + ).toStrictEqual({"1x": 0.5, "2x": 0}); +}); + +test('Pixel ratios 1x, 2x, 3x', () => { + expect( + getCompressionRatio(['1x','2x', '3x']), + ).toStrictEqual({"1x": 0.3333333333333333, "2x": 0.6666666666666666, "3x": 0}); +}); diff --git a/src/utils/__tests__/getOriginalExtensionSrcSet.ts b/src/utils/__tests__/getOriginalExtensionSrcSet.ts new file mode 100644 index 0000000..adf606f --- /dev/null +++ b/src/utils/__tests__/getOriginalExtensionSrcSet.ts @@ -0,0 +1,20 @@ +import { getOriginalExtensionSrcSet } from '../index'; + + +test('Pixel ratios 1x, path "/images/mayImages.png"', () => { + expect( + getOriginalExtensionSrcSet(['1x'],'/images/mayImages.png'), + ).toStrictEqual({"1x": '/images/mayImages.png'}); +}); + +test('Pixel ratios 1x, 2x, path "/images/mayImages.png"', () => { + expect( + getOriginalExtensionSrcSet(['1x','2x'],'/images/mayImages.png'), + ).toStrictEqual({"1x": '/images/mayImages.png', "2x": '/images/mayImages.png'}); +}); + +test('Pixel ratios 1x, 2x, 3x, path "/images/mayImages.png"', () => { + expect( + getOriginalExtensionSrcSet(['1x','2x','3x'],'/images/mayImages.png'), + ).toStrictEqual({"1x": '/images/mayImages.png', "2x": '/images/mayImages.png', "3x": '/images/mayImages.png'}); +}); diff --git a/src/utils/backgroundCss.ts b/src/utils/backgroundCss.ts index d492e3a..4ae2400 100644 --- a/src/utils/backgroundCss.ts +++ b/src/utils/backgroundCss.ts @@ -17,17 +17,17 @@ const srcSetCss = (selector: string, sources: ExtensionSrcSet[]): string => { (acc, source) => { const finalSelector = getSelector(selector, source.extension); acc['1x'].push(`${finalSelector} { background-image: url(${source.srcSet['1x']}); }`); - acc['2x'].push(`${finalSelector} { background-image: url(${source.srcSet['2x']}); }`); - acc['3x'].push(`${finalSelector} { background-image: url(${source.srcSet['3x']}); }`); + source.srcSet['2x'] && acc['2x'].push(`${finalSelector} { background-image: url(${source.srcSet['2x']}); }`); + source.srcSet['3x'] && acc['3x'].push(`${finalSelector} { background-image: url(${source.srcSet['3x']}); }`); return acc; }, { '1x': [], '2x': [], '3x': [] }, ); return ` -${result['1x'].join(' ')} -@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { ${result['2x'].join(' ')} } -@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 288dpi) { ${result['3x'].join(' ')} } + ${result['1x'].join(' ')} + ${result['2x'].length ? `@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { ${result['2x'].join(' ')} }`:''} + ${result['3x'].length ? ` @media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 288dpi) { ${result['3x'].join(' ')} }`:''} `; }; diff --git a/src/utils/getCompressionRatio.ts b/src/utils/getCompressionRatio.ts index 833a3da..05051a1 100644 --- a/src/utils/getCompressionRatio.ts +++ b/src/utils/getCompressionRatio.ts @@ -1,7 +1,5 @@ import { Dpr, CompressionRatio } from '../types'; -// [1x, 2x] -> {1x: 0.5, 2x: 0} - export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { const length = pixelRatios.length; diff --git a/src/utils/getOriginalExtensionSrcSet.ts b/src/utils/getOriginalExtensionSrcSet.ts new file mode 100644 index 0000000..073dac9 --- /dev/null +++ b/src/utils/getOriginalExtensionSrcSet.ts @@ -0,0 +1,8 @@ +import { SrcSet, Dpr } from '../types'; + +export const getOriginalExtensionSrcSet = (pixelRatios: Dpr[], outputImagePath:string):SrcSet => { + return pixelRatios.reduce((acc, item ) => { + acc[item] = outputImagePath; + return acc; + }, {} as SrcSet); +} diff --git a/src/utils/getPixelRations.ts b/src/utils/getPixelRations.ts index 0e7dd4f..710930d 100644 --- a/src/utils/getPixelRations.ts +++ b/src/utils/getPixelRations.ts @@ -8,7 +8,5 @@ export const getPixelRations = (originalPixelRatio: Dpr): Dpr[] => { return ['1x', '2x']; case '3x': return ['1x', '2x', '3x']; - default: - return ['1x']; } }; diff --git a/src/utils/index.ts b/src/utils/index.ts index 370d82a..2931577 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -5,3 +5,4 @@ export { getSources } from './getSources'; export { getOriginal } from './getOriginal'; export { getPixelRations } from './getPixelRations'; export { getCompressionRatio } from './getCompressionRatio'; +export { getOriginalExtensionSrcSet } from './getOriginalExtensionSrcSet'; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index e01ef4d..c291001 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -6,7 +6,7 @@ import { getImgproxyUrlBuilder } from './imgproxyUrlBuilder'; import { Breakpoint, OrderedBreakpointSource, SrcSet, Dpr } from '../types'; import { imageUrls } from './plugin'; import { schema } from './loaderOptionsSchema'; -import { getBreakpointMedia, getPixelRations } from '../utils'; +import { getBreakpointMedia, getPixelRations, getOriginalExtensionSrcSet } from '../utils'; // Такое имя используется, если нужна одна картинка для всех разрешений // В таком случаем не будут сгенерированы медиа выражения для разных breakpoint'ов @@ -30,7 +30,7 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' }); - const pixelRations: Dpr[] = getPixelRations(options.originalPixelRatio); + const pixelRatios: Dpr[] = getPixelRations(options.originalPixelRatio); const breakpoints: Breakpoint[] = options.breakpoints; // Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";' // Получаем оригинальное имя файла изображения (originalImageFileName = mobile.all.png) @@ -70,28 +70,21 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri let webpSrcSet: SrcSet, originalExtensionSrcSet: SrcSet, data: OrderedBreakpointSource; // Отключает процессинг картинок, генерируется srcSet только для оригинального типа изображения if (options.imgproxy.disable) { - // TODO пока не смотрим disable - - originalExtensionSrcSet = { - '1x': outputImagePath, - '2x': outputImagePath, - '3x': outputImagePath, - }; data = { order, breakpointMedia, srcSets: [ { extension: originalExtension, - srcSet: originalExtensionSrcSet, + srcSet: getOriginalExtensionSrcSet(pixelRatios,outputImagePath), }, ], }; } else { const buildUrlsForPixelRatios = getImgproxyUrlBuilder(options.imgproxy); - webpSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, 'webp'); + webpSrcSet = buildUrlsForPixelRatios(pixelRatios, outputImagePath, 'webp'); originalExtensionSrcSet = buildUrlsForPixelRatios( - pixelRations, + pixelRatios, outputImagePath, originalExtension, ); diff --git a/src/webpack/loaderOptionsSchema.ts b/src/webpack/loaderOptionsSchema.ts index 75a554d..133f24b 100644 --- a/src/webpack/loaderOptionsSchema.ts +++ b/src/webpack/loaderOptionsSchema.ts @@ -50,8 +50,9 @@ export const schema: JSONSchema7 = { }, originalPixelRatio: { type: 'string', + pattern: "^(1x|2x|3x)$", }, }, - required: ['breakpoints', 'imgproxy'], + required: ['breakpoints', 'imgproxy','originalPixelRatio'], additionalProperties: false, }; From 03135e1df9c0f1cc52c79d8992ae7c665700c9cd Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Mon, 24 Aug 2020 19:37:36 +0300 Subject: [PATCH 08/11] add type guard for number | undefined in imgproxyUrlBuilder --- src/webpack/imgproxyUrlBuilder.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index 5c93071..546d18f 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -33,7 +33,10 @@ export const getImgproxyUrlBuilder = ({ const compressionsRatio = getCompressionRatio(pixelRatios); return pixelRatios.reduce((acc, item) => { - acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension); + const dprResize = compressionsRatio[item]; + if (dprResize) { + acc[item] = buildImgproxyUrl(imagePath, dprResize, extension); + } return acc; }, {} as SrcSet); }; From 8da663d3a7e2e5f7868a7c7d81bbdf5b271aa1df Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Mon, 24 Aug 2020 19:37:44 +0300 Subject: [PATCH 09/11] lint --- example/react-entry.tsx | 5 +---- src/utils/__tests__/getCompressionRatio.ts | 17 ++++++-------- .../__tests__/getOriginalExtensionSrcSet.ts | 22 ++++++++++--------- src/utils/backgroundCss.ts | 22 +++++++++++++++---- src/utils/getOriginal.ts | 2 +- src/utils/getOriginalExtensionSrcSet.ts | 8 +++---- src/webpack/loader.ts | 2 +- src/webpack/loaderOptionsSchema.ts | 4 ++-- 8 files changed, 46 insertions(+), 36 deletions(-) diff --git a/example/react-entry.tsx b/example/react-entry.tsx index 6771479..4bbfa6c 100644 --- a/example/react-entry.tsx +++ b/example/react-entry.tsx @@ -32,10 +32,7 @@ ReactDOM.render(

Image without resize

- +

As background css

diff --git a/src/utils/__tests__/getCompressionRatio.ts b/src/utils/__tests__/getCompressionRatio.ts index b58f33b..e82197c 100644 --- a/src/utils/__tests__/getCompressionRatio.ts +++ b/src/utils/__tests__/getCompressionRatio.ts @@ -1,20 +1,17 @@ import { getCompressionRatio } from '../index'; - test('Pixel ratios 1x', () => { - expect( - getCompressionRatio(['1x']), - ).toStrictEqual({"1x": 0}); + expect(getCompressionRatio(['1x'])).toStrictEqual({ '1x': 0 }); }); test('Pixel ratios 1x, 2x', () => { - expect( - getCompressionRatio(['1x','2x']), - ).toStrictEqual({"1x": 0.5, "2x": 0}); + expect(getCompressionRatio(['1x', '2x'])).toStrictEqual({ '1x': 0.5, '2x': 0 }); }); test('Pixel ratios 1x, 2x, 3x', () => { - expect( - getCompressionRatio(['1x','2x', '3x']), - ).toStrictEqual({"1x": 0.3333333333333333, "2x": 0.6666666666666666, "3x": 0}); + expect(getCompressionRatio(['1x', '2x', '3x'])).toStrictEqual({ + '1x': 0.3333333333333333, + '2x': 0.6666666666666666, + '3x': 0, + }); }); diff --git a/src/utils/__tests__/getOriginalExtensionSrcSet.ts b/src/utils/__tests__/getOriginalExtensionSrcSet.ts index adf606f..3fb4722 100644 --- a/src/utils/__tests__/getOriginalExtensionSrcSet.ts +++ b/src/utils/__tests__/getOriginalExtensionSrcSet.ts @@ -1,20 +1,22 @@ import { getOriginalExtensionSrcSet } from '../index'; - test('Pixel ratios 1x, path "/images/mayImages.png"', () => { - expect( - getOriginalExtensionSrcSet(['1x'],'/images/mayImages.png'), - ).toStrictEqual({"1x": '/images/mayImages.png'}); + expect(getOriginalExtensionSrcSet(['1x'], '/images/mayImages.png')).toStrictEqual({ + '1x': '/images/mayImages.png', + }); }); test('Pixel ratios 1x, 2x, path "/images/mayImages.png"', () => { - expect( - getOriginalExtensionSrcSet(['1x','2x'],'/images/mayImages.png'), - ).toStrictEqual({"1x": '/images/mayImages.png', "2x": '/images/mayImages.png'}); + expect(getOriginalExtensionSrcSet(['1x', '2x'], '/images/mayImages.png')).toStrictEqual({ + '1x': '/images/mayImages.png', + '2x': '/images/mayImages.png', + }); }); test('Pixel ratios 1x, 2x, 3x, path "/images/mayImages.png"', () => { - expect( - getOriginalExtensionSrcSet(['1x','2x','3x'],'/images/mayImages.png'), - ).toStrictEqual({"1x": '/images/mayImages.png', "2x": '/images/mayImages.png', "3x": '/images/mayImages.png'}); + expect(getOriginalExtensionSrcSet(['1x', '2x', '3x'], '/images/mayImages.png')).toStrictEqual({ + '1x': '/images/mayImages.png', + '2x': '/images/mayImages.png', + '3x': '/images/mayImages.png', + }); }); diff --git a/src/utils/backgroundCss.ts b/src/utils/backgroundCss.ts index 4ae2400..19e04dd 100644 --- a/src/utils/backgroundCss.ts +++ b/src/utils/backgroundCss.ts @@ -17,8 +17,10 @@ const srcSetCss = (selector: string, sources: ExtensionSrcSet[]): string => { (acc, source) => { const finalSelector = getSelector(selector, source.extension); acc['1x'].push(`${finalSelector} { background-image: url(${source.srcSet['1x']}); }`); - source.srcSet['2x'] && acc['2x'].push(`${finalSelector} { background-image: url(${source.srcSet['2x']}); }`); - source.srcSet['3x'] && acc['3x'].push(`${finalSelector} { background-image: url(${source.srcSet['3x']}); }`); + source.srcSet['2x'] && + acc['2x'].push(`${finalSelector} { background-image: url(${source.srcSet['2x']}); }`); + source.srcSet['3x'] && + acc['3x'].push(`${finalSelector} { background-image: url(${source.srcSet['3x']}); }`); return acc; }, { '1x': [], '2x': [], '3x': [] }, @@ -26,8 +28,20 @@ const srcSetCss = (selector: string, sources: ExtensionSrcSet[]): string => { return ` ${result['1x'].join(' ')} - ${result['2x'].length ? `@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { ${result['2x'].join(' ')} }`:''} - ${result['3x'].length ? ` @media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 288dpi) { ${result['3x'].join(' ')} }`:''} + ${ + result['2x'].length + ? `@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { ${result['2x'].join( + ' ', + )} }` + : '' + } + ${ + result['3x'].length + ? ` @media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 288dpi) { ${result[ + '3x' + ].join(' ')} }` + : '' + } `; }; diff --git a/src/utils/getOriginal.ts b/src/utils/getOriginal.ts index de2a197..03fa628 100644 --- a/src/utils/getOriginal.ts +++ b/src/utils/getOriginal.ts @@ -1,6 +1,6 @@ import { BreakpointSource } from '../types'; -export const getOriginal = (source: BreakpointSource) => { +export const getOriginal = (source: BreakpointSource): string => { const srcSet = source.srcSets[source.srcSets.length - 1].srcSet; return srcSet['3x'] || srcSet['2x'] || srcSet['1x']; diff --git a/src/utils/getOriginalExtensionSrcSet.ts b/src/utils/getOriginalExtensionSrcSet.ts index 073dac9..9938887 100644 --- a/src/utils/getOriginalExtensionSrcSet.ts +++ b/src/utils/getOriginalExtensionSrcSet.ts @@ -1,8 +1,8 @@ import { SrcSet, Dpr } from '../types'; -export const getOriginalExtensionSrcSet = (pixelRatios: Dpr[], outputImagePath:string):SrcSet => { - return pixelRatios.reduce((acc, item ) => { - acc[item] = outputImagePath; +export const getOriginalExtensionSrcSet = (pixelRatios: Dpr[], outputImagePath: string): SrcSet => { + return pixelRatios.reduce((acc, item) => { + acc[item] = outputImagePath; return acc; }, {} as SrcSet); -} +}; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index c291001..ca17c76 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -76,7 +76,7 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri srcSets: [ { extension: originalExtension, - srcSet: getOriginalExtensionSrcSet(pixelRatios,outputImagePath), + srcSet: getOriginalExtensionSrcSet(pixelRatios, outputImagePath), }, ], }; diff --git a/src/webpack/loaderOptionsSchema.ts b/src/webpack/loaderOptionsSchema.ts index 133f24b..c3c8326 100644 --- a/src/webpack/loaderOptionsSchema.ts +++ b/src/webpack/loaderOptionsSchema.ts @@ -50,9 +50,9 @@ export const schema: JSONSchema7 = { }, originalPixelRatio: { type: 'string', - pattern: "^(1x|2x|3x)$", + pattern: '^(1x|2x|3x)$', }, }, - required: ['breakpoints', 'imgproxy','originalPixelRatio'], + required: ['breakpoints', 'imgproxy', 'originalPixelRatio'], additionalProperties: false, }; From 9c2a46957c51a370258123ef044ef95ed10c86b9 Mon Sep 17 00:00:00 2001 From: yankovskyandrey Date: Tue, 25 Aug 2020 09:55:12 +0300 Subject: [PATCH 10/11] Fixed incorrect check that interpret 0 as falsy value --- src/webpack/imgproxyUrlBuilder.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webpack/imgproxyUrlBuilder.ts b/src/webpack/imgproxyUrlBuilder.ts index 546d18f..f0dd5fc 100644 --- a/src/webpack/imgproxyUrlBuilder.ts +++ b/src/webpack/imgproxyUrlBuilder.ts @@ -34,7 +34,7 @@ export const getImgproxyUrlBuilder = ({ return pixelRatios.reduce((acc, item) => { const dprResize = compressionsRatio[item]; - if (dprResize) { + if (dprResize !== undefined) { acc[item] = buildImgproxyUrl(imagePath, dprResize, extension); } return acc; From 8b2dfa4573cb5bff5fbbfb38bd1c9a980516c5a6 Mon Sep 17 00:00:00 2001 From: Viktor Kosinov Date: Tue, 25 Aug 2020 10:38:14 +0300 Subject: [PATCH 11/11] COM-2479: - add rounding to getCompressionRatio - rename getPixelRations -> getPixelRatios - refactoring use getOriginalExtensionSrcSet --- src/utils/__tests__/getCompressionRatio.ts | 4 ++-- .../__tests__/getOriginalExtensionSrcSet.ts | 22 ------------------- src/utils/getCompressionRatio.ts | 2 +- src/utils/getOriginalExtensionSrcSet.ts | 8 ------- .../{getPixelRations.ts => getPixelRatios.ts} | 2 +- src/utils/index.ts | 3 +-- src/webpack/loader.ts | 9 +++++--- 7 files changed, 11 insertions(+), 39 deletions(-) delete mode 100644 src/utils/__tests__/getOriginalExtensionSrcSet.ts delete mode 100644 src/utils/getOriginalExtensionSrcSet.ts rename src/utils/{getPixelRations.ts => getPixelRatios.ts} (74%) diff --git a/src/utils/__tests__/getCompressionRatio.ts b/src/utils/__tests__/getCompressionRatio.ts index e82197c..591e5ef 100644 --- a/src/utils/__tests__/getCompressionRatio.ts +++ b/src/utils/__tests__/getCompressionRatio.ts @@ -10,8 +10,8 @@ test('Pixel ratios 1x, 2x', () => { test('Pixel ratios 1x, 2x, 3x', () => { expect(getCompressionRatio(['1x', '2x', '3x'])).toStrictEqual({ - '1x': 0.3333333333333333, - '2x': 0.6666666666666666, + '1x': 0.33333, + '2x': 0.66667, '3x': 0, }); }); diff --git a/src/utils/__tests__/getOriginalExtensionSrcSet.ts b/src/utils/__tests__/getOriginalExtensionSrcSet.ts deleted file mode 100644 index 3fb4722..0000000 --- a/src/utils/__tests__/getOriginalExtensionSrcSet.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { getOriginalExtensionSrcSet } from '../index'; - -test('Pixel ratios 1x, path "/images/mayImages.png"', () => { - expect(getOriginalExtensionSrcSet(['1x'], '/images/mayImages.png')).toStrictEqual({ - '1x': '/images/mayImages.png', - }); -}); - -test('Pixel ratios 1x, 2x, path "/images/mayImages.png"', () => { - expect(getOriginalExtensionSrcSet(['1x', '2x'], '/images/mayImages.png')).toStrictEqual({ - '1x': '/images/mayImages.png', - '2x': '/images/mayImages.png', - }); -}); - -test('Pixel ratios 1x, 2x, 3x, path "/images/mayImages.png"', () => { - expect(getOriginalExtensionSrcSet(['1x', '2x', '3x'], '/images/mayImages.png')).toStrictEqual({ - '1x': '/images/mayImages.png', - '2x': '/images/mayImages.png', - '3x': '/images/mayImages.png', - }); -}); diff --git a/src/utils/getCompressionRatio.ts b/src/utils/getCompressionRatio.ts index 05051a1..cc122db 100644 --- a/src/utils/getCompressionRatio.ts +++ b/src/utils/getCompressionRatio.ts @@ -9,7 +9,7 @@ export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => { return acc; } - acc[item] = (index + 1) / length; + acc[item] = Number(((index + 1) / length).toFixed(5)); return acc; }, {} as CompressionRatio); }; diff --git a/src/utils/getOriginalExtensionSrcSet.ts b/src/utils/getOriginalExtensionSrcSet.ts deleted file mode 100644 index 9938887..0000000 --- a/src/utils/getOriginalExtensionSrcSet.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { SrcSet, Dpr } from '../types'; - -export const getOriginalExtensionSrcSet = (pixelRatios: Dpr[], outputImagePath: string): SrcSet => { - return pixelRatios.reduce((acc, item) => { - acc[item] = outputImagePath; - return acc; - }, {} as SrcSet); -}; diff --git a/src/utils/getPixelRations.ts b/src/utils/getPixelRatios.ts similarity index 74% rename from src/utils/getPixelRations.ts rename to src/utils/getPixelRatios.ts index 710930d..0d4dacd 100644 --- a/src/utils/getPixelRations.ts +++ b/src/utils/getPixelRatios.ts @@ -1,6 +1,6 @@ import { Dpr } from '../types'; -export const getPixelRations = (originalPixelRatio: Dpr): Dpr[] => { +export const getPixelRatios = (originalPixelRatio: Dpr): Dpr[] => { switch (originalPixelRatio) { case '1x': return ['1x']; diff --git a/src/utils/index.ts b/src/utils/index.ts index 2931577..9f6e826 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -3,6 +3,5 @@ export { getBreakpointMedia } from './getBreakpointMedia'; export { getSrcSetString } from './getSrcSetString'; export { getSources } from './getSources'; export { getOriginal } from './getOriginal'; -export { getPixelRations } from './getPixelRations'; +export { getPixelRatios } from './getPixelRatios'; export { getCompressionRatio } from './getCompressionRatio'; -export { getOriginalExtensionSrcSet } from './getOriginalExtensionSrcSet'; diff --git a/src/webpack/loader.ts b/src/webpack/loader.ts index ca17c76..28ff2c9 100644 --- a/src/webpack/loader.ts +++ b/src/webpack/loader.ts @@ -6,7 +6,7 @@ import { getImgproxyUrlBuilder } from './imgproxyUrlBuilder'; import { Breakpoint, OrderedBreakpointSource, SrcSet, Dpr } from '../types'; import { imageUrls } from './plugin'; import { schema } from './loaderOptionsSchema'; -import { getBreakpointMedia, getPixelRations, getOriginalExtensionSrcSet } from '../utils'; +import { getBreakpointMedia, getPixelRatios } from '../utils'; // Такое имя используется, если нужна одна картинка для всех разрешений // В таком случаем не будут сгенерированы медиа выражения для разных breakpoint'ов @@ -30,7 +30,7 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' }); - const pixelRatios: Dpr[] = getPixelRations(options.originalPixelRatio); + const pixelRatios: Dpr[] = getPixelRatios(options.originalPixelRatio); const breakpoints: Breakpoint[] = options.breakpoints; // Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";' // Получаем оригинальное имя файла изображения (originalImageFileName = mobile.all.png) @@ -76,7 +76,10 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri srcSets: [ { extension: originalExtension, - srcSet: getOriginalExtensionSrcSet(pixelRatios, outputImagePath), + srcSet: pixelRatios.reduce((acc, item): SrcSet => { + acc[item] = outputImagePath; + return acc; + }, {} as SrcSet), }, ], };