UNPKG

2.01 kBJavaScriptView Raw
1"use strict";
2
3const htmlMinifier = require('html-minifier-terser');
4
5const defaultMinimizerOptions = {
6 caseSensitive: true,
7 // `collapseBooleanAttributes` is not always safe, since this can break CSS attribute selectors and not safe for XHTML
8 collapseWhitespace: true,
9 conservativeCollapse: true,
10 keepClosingSlash: true,
11 // We need ability to use cssnano, or setup own function without extra dependencies
12 minifyCSS: true,
13 minifyJS: true,
14 // `minifyURLs` is unsafe, because we can't guarantee what the base URL is
15 // `removeAttributeQuotes` is not safe in some rare cases, also HTML spec recommends against doing this
16 removeComments: true,
17 // `removeEmptyAttributes` is not safe, can affect certain style or script behavior, look at https://github.com/webpack-contrib/html-loader/issues/323
18 // `removeRedundantAttributes` is not safe, can affect certain style or script behavior, look at https://github.com/webpack-contrib/html-loader/issues/323
19 removeScriptTypeAttributes: true,
20 removeStyleLinkTypeAttributes: true // `useShortDoctype` is not safe for XHTML
21
22};
23
24const minify = async options => {
25 const {
26 assetName,
27 input,
28 minimizerOptions,
29 minify: minifyFn
30 } = options;
31
32 if (minifyFn) {
33 const result = await minifyFn({
34 [assetName]: input
35 }, minimizerOptions);
36 return {
37 html: result
38 };
39 }
40
41 const result = await htmlMinifier.minify(input, { ...defaultMinimizerOptions,
42 ...minimizerOptions
43 });
44 return {
45 html: result
46 };
47};
48
49async function transform(options) {
50 // 'use strict' => this === undefined (Clean Scope)
51 // Safer for possible security issues, albeit not critical at all here
52 // eslint-disable-next-line no-new-func, no-param-reassign
53 options = new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
54 return minify(options);
55}
56
57module.exports.minify = minify;
58module.exports.transform = transform;
\No newline at end of file