Skip to content

Instantly share code, notes, and snippets.

@zachleat
Last active August 25, 2022 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachleat/aa7a538e52a507bd4d867e385ea60720 to your computer and use it in GitHub Desktop.
Save zachleat/aa7a538e52a507bd4d867e385ea60720 to your computer and use it in GitHub Desktop.
JSMin filter with a cache
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