Last active
August 25, 2022 13:37
-
-
Save zachleat/aa7a538e52a507bd4d867e385ea60720 to your computer and use it in GitHub Desktop.
JSMin filter with a cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { minify } = require('terser'); | |
const jsMinCache = {}; | |
module.exports = function (eleventyConfig) { | |
eleventyConfig.addNunjucksAsyncFilter('jsmin', async function (code, callback) { | |
try { | |
if(jsMinCache[code]) { | |
callback(null, jsMinCache[code]); | |
} else { | |
const minified = await minify(code); | |
jsMinCache[code] = minified.code; | |
callback(null, minified.code); | |
} | |
} catch (err) { | |
console.error('Terser error: ', err); | |
delete jsMinCache[code]; | |
callback(null, code); // Fail gracefully. | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment