From 42e78df4dbc3d6c34834657d6decc1bf3904a3ee Mon Sep 17 00:00:00 2001 From: Justin Halsall Date: Thu, 21 Jan 2021 16:57:23 +0100 Subject: [PATCH] largeFileCallback support --- README.md | 9 +++++++++ index.js | 1 + lib/image.js | 5 +++++ test/fixtures/styles/big.modified.css | 3 +++ test/test.js | 8 ++++++++ 5 files changed, 26 insertions(+) create mode 100644 test/fixtures/styles/big.modified.css diff --git a/README.md b/README.md index cd26a79..6d95a3a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,15 @@ You can define local directories (globs supported) or URLs. Sets a max file size (in bytes) for inlined images. Set to `0` to disable size checking. +#### largeFileCallback + +* Type: `function` +* Default: undefined +* Example: `function (file) { console.log('big file found:', file.path); return file.path }` +* Required: `false` + +Allows you to act on large files and change the url if you'd like. Make sure you have `strict` set to `false` when using this. + #### b64Svg * Type: `bool` diff --git a/index.js b/index.js index 6e31189..a35171e 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,7 @@ const DEFAULTS = { maxFileSize: 10240, b64Svg: false, strict: false, + largeFileCallback: undefined, }; const loop = (cb) => { diff --git a/lib/image.js b/lib/image.js index f30add3..b56865f 100644 --- a/lib/image.js +++ b/lib/image.js @@ -80,6 +80,11 @@ function getDataUriMapping(urls = [], options = {}) { const file = await resolve(url, options); if (file && file.mime && /image/.test(file.mime)) { result[url] = await getDataUri(file, options); + } else if (options.largeFileCallback) { + const largeFile = await resolve(url, {...options, maxFileSize: 0}); + if (largeFile && largeFile.mime && /image/.test(largeFile.mime)) { + result[url] = await options.largeFileCallback(largeFile); + } } return result; diff --git a/test/fixtures/styles/big.modified.css b/test/fixtures/styles/big.modified.css new file mode 100644 index 0000000..28bba40 --- /dev/null +++ b/test/fixtures/styles/big.modified.css @@ -0,0 +1,3 @@ +.big { + background-image: url('https://cdn.example.com/images/blank.gif'); +} diff --git a/test/test.js b/test/test.js index 4a5d185..d1a79e9 100644 --- a/test/test.js +++ b/test/test.js @@ -59,6 +59,14 @@ describe('postcss-image-inliner', () => { test('big.css', 'big.css', {maxFileSize: 1}, done); }); + it('should trigger callback on too big images', (done) => { + const largeFileCallback = (file) => { + return file.path.replace('http://localhost:3000/', 'https://cdn.example.com/'); + }; + + test('big.css', 'big.modified.css', {maxFileSize: 1, largeFileCallback}, done); + }); + it('should handle multiple background images', (done) => { test('multi.in.css', 'multi.out.css', {}, done); });