Skip to content

Commit

Permalink
only require and process using sharp when really required (#4976)
Browse files Browse the repository at this point in the history
  • Loading branch information
DeMoorJasper committed Aug 6, 2020
1 parent a1bf63d commit 46e8ffa
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
4 changes: 3 additions & 1 deletion packages/transformers/image/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"parcel": "^2.0.0-beta.1"
},
"dependencies": {
"@parcel/plugin": "^2.0.0-beta.1",
"@parcel/plugin": "^2.0.0-beta.1"
},
"devDependencies": {
"sharp": "^0.24.1"
}
}
44 changes: 27 additions & 17 deletions packages/transformers/image/src/ImageTransformer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// @flow
import {Transformer} from '@parcel/plugin';
import sharp from 'sharp';

const FORMATS = new Map([
['heic', 'heif'],
Expand All @@ -14,35 +13,46 @@ const FORMATS = new Map([
]);

export default (new Transformer({
async transform({asset}) {
async transform({asset, options}) {
asset.isIsolated = true;

let inputBuffer = await asset.getBuffer();
let width = asset.query.width ? parseInt(asset.query.width, 10) : null;
let height = asset.query.height ? parseInt(asset.query.height, 10) : null;
let quality = asset.query.quality
? parseInt(asset.query.quality, 10)
: undefined;
let format = asset.query.as ? asset.query.as.toLowerCase().trim() : null;

let imagePipeline = sharp(inputBuffer);
if (width || height) {
imagePipeline.resize(width, height);
}

if (format) {
if (!FORMATS.has(format)) {
throw new Error(`Sharp does not support ${format} images.`);
if (width || height || quality || format) {
const sharp = await options.packageManager.require(
'sharp',
asset.filePath,
{
// Sharp takes too long to install for autoinstall option to make sense
autoinstall: false,
},
);

let inputBuffer = await asset.getBuffer();
let imagePipeline = sharp(inputBuffer);
if (width || height) {
imagePipeline.resize(width, height);
}

asset.type = format;
if (format) {
if (!FORMATS.has(format)) {
throw new Error(`Sharp does not support ${format} images.`);
}

imagePipeline[FORMATS.get(format)]({
quality,
});
}
asset.type = format;

asset.setStream(imagePipeline);
imagePipeline[FORMATS.get(format)]({
quality,
});
}

asset.setStream(imagePipeline);
}

return [asset];
},
Expand Down

0 comments on commit 46e8ffa

Please sign in to comment.