_includes/filters/minify-js.js

/**
* @file Defines a filter to minify JavaScript inline
* @author Reuben L. Lillie <reubenlillie@gmail.com>
* @see {@link https://www.11ty.dev/docs/filters/ Filters in 11ty}
*/


/*
* Import Terser module
* @see {@link https://github.com/terser-js/terser GitHub}
*/

import Terser from 'terser'

/**
* An Eleventy filter for minifying JavaScript inline
* @module _includes/filters/minify-js
* @param {Object} eleventyConfig 11ty’s Config API
*/

export default function (eleventyConfig) {

/**
* Minify JavaScript
* @param {String} code A JavaScript file’s contents
* @return {String} The minified script
* @example `${this.minifyJS($this.fileToString('/includes/assets/js/gratuitip.js'))}`
* See {@link https://www.11ty.dev/docs/quicktips/inline-js/ 11ty docs}
*/

eleventyConfig.addFilter("minifyJS", function(code) {
var minified = Terser.minify(code)
if(minified.error) {
console.log("Terser error: ", minified.error)
return code
}

return minified.code
})

}