cli.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #!/usr/bin/env node
  2. /**
  3. * html-minifier CLI tool
  4. *
  5. * The MIT License (MIT)
  6. *
  7. * Copyright (c) 2014-2016 Zoltan Frombach
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  10. * this software and associated documentation files (the "Software"), to deal in
  11. * the Software without restriction, including without limitation the rights to
  12. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  13. * the Software, and to permit persons to whom the Software is furnished to do so,
  14. * subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in all
  17. * copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  21. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  22. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  23. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  24. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. *
  26. */
  27. 'use strict';
  28. var camelCase = require('camel-case');
  29. var fs = require('fs');
  30. var info = require('./package.json');
  31. var minify = require('./' + info.main).minify;
  32. var paramCase = require('param-case');
  33. var path = require('path');
  34. var program = require('commander');
  35. program._name = info.name;
  36. program.version(info.version);
  37. function fatal(message) {
  38. console.error(message);
  39. process.exit(1);
  40. }
  41. /**
  42. * JSON does not support regexes, so, e.g., JSON.parse() will not create
  43. * a RegExp from the JSON value `[ "/matchString/" ]`, which is
  44. * technically just an array containing a string that begins and end with
  45. * a forward slash. To get a RegExp from a JSON string, it must be
  46. * constructed explicitly in JavaScript.
  47. *
  48. * The likelihood of actually wanting to match text that is enclosed in
  49. * forward slashes is probably quite rare, so if forward slashes were
  50. * included in an argument that requires a regex, the user most likely
  51. * thought they were part of the syntax for specifying a regex.
  52. *
  53. * In the unlikely case that forward slashes are indeed desired in the
  54. * search string, the user would need to enclose the expression in a
  55. * second set of slashes:
  56. *
  57. * --customAttrSrround "[\"//matchString//\"]"
  58. */
  59. function parseRegExp(value) {
  60. if (value) {
  61. return new RegExp(value.replace(/^\/(.*)\/$/, '$1'));
  62. }
  63. }
  64. function parseJSON(value) {
  65. if (value) {
  66. try {
  67. return JSON.parse(value);
  68. }
  69. catch (e) {
  70. if (/^{/.test(value)) {
  71. fatal('Could not parse JSON value \'' + value + '\'');
  72. }
  73. return value;
  74. }
  75. }
  76. }
  77. function parseJSONArray(value) {
  78. if (value) {
  79. value = parseJSON(value);
  80. return Array.isArray(value) ? value : [value];
  81. }
  82. }
  83. function parseJSONRegExpArray(value) {
  84. value = parseJSONArray(value);
  85. return value && value.map(parseRegExp);
  86. }
  87. function parseString(value) {
  88. return value;
  89. }
  90. var mainOptions = {
  91. caseSensitive: 'Treat attributes in case sensitive manner (useful for SVG; e.g. viewBox)',
  92. collapseBooleanAttributes: 'Omit attribute values from boolean attributes',
  93. collapseInlineTagWhitespace: 'Collapse white space around inline tag',
  94. collapseWhitespace: 'Collapse white space that contributes to text nodes in a document tree.',
  95. conservativeCollapse: 'Always collapse to 1 space (never remove it entirely)',
  96. customAttrAssign: ['Arrays of regex\'es that allow to support custom attribute assign expressions (e.g. \'<div flex?="{{mode != cover}}"></div>\')', parseJSONRegExpArray],
  97. customAttrCollapse: ['Regex that specifies custom attribute to strip newlines from (e.g. /ng-class/)', parseRegExp],
  98. customAttrSurround: ['Arrays of regex\'es that allow to support custom attribute surround expressions (e.g. <input {{#if value}}checked="checked"{{/if}}>)', parseJSONRegExpArray],
  99. customEventAttributes: ['Arrays of regex\'es that allow to support custom event attributes for minifyJS (e.g. ng-click)', parseJSONRegExpArray],
  100. decodeEntities: 'Use direct Unicode characters whenever possible',
  101. html5: 'Parse input according to HTML5 specifications',
  102. ignoreCustomComments: ['Array of regex\'es that allow to ignore certain comments, when matched', parseJSONRegExpArray],
  103. ignoreCustomFragments: ['Array of regex\'es that allow to ignore certain fragments, when matched (e.g. <?php ... ?>, {{ ... }})', parseJSONRegExpArray],
  104. includeAutoGeneratedTags: 'Insert tags generated by HTML parser',
  105. keepClosingSlash: 'Keep the trailing slash on singleton elements',
  106. maxLineLength: ['Max line length', parseInt],
  107. minifyCSS: ['Minify CSS in style elements and style attributes (uses clean-css)', parseJSON],
  108. minifyJS: ['Minify Javascript in script elements and on* attributes (uses uglify-js)', parseJSON],
  109. minifyURLs: ['Minify URLs in various attributes (uses relateurl)', parseJSON],
  110. preserveLineBreaks: 'Always collapse to 1 line break (never remove it entirely) when whitespace between tags include a line break.',
  111. preventAttributesEscaping: 'Prevents the escaping of the values of attributes.',
  112. processConditionalComments: 'Process contents of conditional comments through minifier',
  113. processScripts: ['Array of strings corresponding to types of script elements to process through minifier (e.g. "text/ng-template", "text/x-handlebars-template", etc.)', parseJSONArray],
  114. quoteCharacter: ['Type of quote to use for attribute values (\' or ")', parseString],
  115. removeAttributeQuotes: 'Remove quotes around attributes when possible.',
  116. removeComments: 'Strip HTML comments',
  117. removeEmptyAttributes: 'Remove all attributes with whitespace-only values',
  118. removeEmptyElements: 'Remove all elements with empty contents',
  119. removeOptionalTags: 'Remove unrequired tags',
  120. removeRedundantAttributes: 'Remove attributes when value matches default.',
  121. removeScriptTypeAttributes: 'Remove type="text/javascript" from script tags. Other type attribute values are left intact.',
  122. removeStyleLinkTypeAttributes: 'Remove type="text/css" from style and link tags. Other type attribute values are left intact.',
  123. removeTagWhitespace: 'Remove space between attributes whenever possible',
  124. sortAttributes: 'Sort attributes by frequency',
  125. sortClassName: 'Sort style classes by frequency',
  126. trimCustomFragments: 'Trim white space around ignoreCustomFragments.',
  127. useShortDoctype: 'Replaces the doctype with the short (HTML5) doctype'
  128. };
  129. var mainOptionKeys = Object.keys(mainOptions);
  130. mainOptionKeys.forEach(function(key) {
  131. var option = mainOptions[key];
  132. if (Array.isArray(option)) {
  133. key = key === 'minifyURLs' ? '--minify-urls' : '--' + paramCase(key);
  134. key += option[1] === parseJSON ? ' [value]' : ' <value>';
  135. program.option(key, option[0], option[1]);
  136. }
  137. else if (~['html5', 'includeAutoGeneratedTags'].indexOf(key)) {
  138. program.option('--no-' + paramCase(key), option);
  139. }
  140. else {
  141. program.option('--' + paramCase(key), option);
  142. }
  143. });
  144. program.option('-o --output <file>', 'Specify output file (if not specified STDOUT will be used for output)');
  145. function readFile(file) {
  146. try {
  147. return fs.readFileSync(file, { encoding: 'utf8' });
  148. }
  149. catch (e) {
  150. fatal('Cannot read ' + file + '\n' + e.message);
  151. }
  152. }
  153. var config = {};
  154. program.option('-c --config-file <file>', 'Use config file', function(configPath) {
  155. var data = readFile(configPath);
  156. try {
  157. config = JSON.parse(data);
  158. }
  159. catch (je) {
  160. try {
  161. config = require(path.resolve(configPath));
  162. }
  163. catch (ne) {
  164. fatal('Cannot read the specified config file.\nAs JSON: ' + je.message + '\nAs module: ' + ne.message);
  165. }
  166. }
  167. mainOptionKeys.forEach(function(key) {
  168. if (key in config) {
  169. var option = mainOptions[key];
  170. if (Array.isArray(option)) {
  171. var value = config[key];
  172. config[key] = option[1](typeof value === 'string' ? value : JSON.stringify(value));
  173. }
  174. }
  175. });
  176. });
  177. program.option('--input-dir <dir>', 'Specify an input directory');
  178. program.option('--output-dir <dir>', 'Specify an output directory');
  179. program.option('--file-ext <text>', 'Specify an extension to be read, ex: html');
  180. var content;
  181. program.arguments('[files...]').action(function(files) {
  182. content = files.map(readFile).join('');
  183. }).parse(process.argv);
  184. function createOptions() {
  185. var options = {};
  186. mainOptionKeys.forEach(function(key) {
  187. var param = program[camelCase(key)];
  188. if (typeof param !== 'undefined') {
  189. options[key] = param;
  190. }
  191. else if (key in config) {
  192. options[key] = config[key];
  193. }
  194. });
  195. return options;
  196. }
  197. function mkdir(outputDir, callback) {
  198. fs.mkdir(outputDir, function(err) {
  199. if (err) {
  200. switch (err.code) {
  201. case 'ENOENT':
  202. return mkdir(path.join(outputDir, '..'), function() {
  203. mkdir(outputDir, callback);
  204. });
  205. case 'EEXIST':
  206. break;
  207. default:
  208. fatal('Cannot create directory ' + outputDir + '\n' + err.message);
  209. }
  210. }
  211. callback();
  212. });
  213. }
  214. function processFile(inputFile, outputFile) {
  215. fs.readFile(inputFile, { encoding: 'utf8' }, function(err, data) {
  216. if (err) {
  217. fatal('Cannot read ' + inputFile + '\n' + err.message);
  218. }
  219. var minified;
  220. try {
  221. minified = minify(data, createOptions());
  222. }
  223. catch (e) {
  224. fatal('Minification error on ' + inputFile + '\n' + e.message);
  225. }
  226. fs.writeFile(outputFile, minified, { encoding: 'utf8' }, function(err) {
  227. if (err) {
  228. fatal('Cannot write ' + outputFile + '\n' + err.message);
  229. }
  230. });
  231. });
  232. }
  233. function processDirectory(inputDir, outputDir, fileExt) {
  234. fs.readdir(inputDir, function(err, files) {
  235. if (err) {
  236. fatal('Cannot read directory ' + inputDir + '\n' + err.message);
  237. }
  238. files.forEach(function(file) {
  239. var inputFile = path.join(inputDir, file);
  240. var outputFile = path.join(outputDir, file);
  241. fs.stat(inputFile, function(err, stat) {
  242. if (err) {
  243. fatal('Cannot read ' + inputFile + '\n' + err.message);
  244. }
  245. else if (stat.isDirectory()) {
  246. processDirectory(inputFile, outputFile, fileExt);
  247. }
  248. else if (!fileExt || path.extname(file) === '.' + fileExt) {
  249. mkdir(outputDir, function() {
  250. processFile(inputFile, outputFile);
  251. });
  252. }
  253. });
  254. });
  255. });
  256. }
  257. function writeMinify() {
  258. var minified;
  259. try {
  260. minified = minify(content, createOptions());
  261. }
  262. catch (e) {
  263. fatal('Minification error:\n' + e.message);
  264. }
  265. (program.output ? fs.createWriteStream(program.output).on('error', function(e) {
  266. fatal('Cannot write ' + program.output + '\n' + e.message);
  267. }) : process.stdout).write(minified);
  268. }
  269. var inputDir = program.inputDir;
  270. var outputDir = program.outputDir;
  271. var fileExt = program.fileExt;
  272. if (inputDir || outputDir) {
  273. if (!inputDir) {
  274. fatal('The option output-dir needs to be used with the option input-dir. If you are working with a single file, use -o.');
  275. }
  276. else if (!outputDir) {
  277. fatal('You need to specify where to write the output files with the option --output-dir');
  278. }
  279. processDirectory(inputDir, outputDir, fileExt);
  280. }
  281. // Minifying one or more files specified on the CMD line
  282. else if (typeof content === 'string') {
  283. writeMinify();
  284. }
  285. // Minifying input coming from STDIN
  286. else {
  287. content = '';
  288. process.stdin.setEncoding('utf8');
  289. process.stdin.on('data', function(data) {
  290. content += data;
  291. }).on('end', writeMinify);
  292. }