Nav apraksta

uglifyjs 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. #! /usr/bin/env node
  2. // -*- js -*-
  3. "use strict";
  4. var UglifyJS = require("../tools/node");
  5. var sys = require("util");
  6. var yargs = require("yargs");
  7. var fs = require("fs");
  8. var path = require("path");
  9. var async = require("async");
  10. var acorn;
  11. var ARGS = yargs
  12. .usage("$0 input1.js [input2.js ...] [options]\n\
  13. Use a single dash to read input from the standard input.\
  14. \n\n\
  15. NOTE: by default there is no mangling/compression.\n\
  16. Without [options] it will simply parse input files and dump the AST\n\
  17. with whitespace and comments discarded. To achieve compression and\n\
  18. mangling you need to use `-c` and `-m`.\
  19. ")
  20. .describe("source-map", "Specify an output file where to generate source map.")
  21. .describe("source-map-root", "The path to the original source to be included in the source map.")
  22. .describe("source-map-url", "The path to the source map to be added in //# sourceMappingURL. Defaults to the value passed with --source-map.")
  23. .describe("source-map-include-sources", "Pass this flag if you want to include the content of source files in the source map as sourcesContent property.")
  24. .describe("in-source-map", "Input source map, useful if you're compressing JS that was generated from some other original code.")
  25. .describe("screw-ie8", "Pass this flag if you don't care about full compliance with Internet Explorer 6-8 quirks (by default UglifyJS will try to be IE-proof).")
  26. .describe("expr", "Parse a single expression, rather than a program (for parsing JSON)")
  27. .describe("p", "Skip prefix for original filenames that appear in source maps. \
  28. For example -p 3 will drop 3 directories from file names and ensure they are relative paths. \
  29. You can also specify -p relative, which will make UglifyJS figure out itself the relative paths between original sources, \
  30. the source map and the output file.")
  31. .describe("o", "Output file (default STDOUT).")
  32. .describe("b", "Beautify output/specify output options.")
  33. .describe("m", "Mangle names/pass mangler options.")
  34. .describe("r", "Reserved names to exclude from mangling.")
  35. .describe("c", "Enable compressor/pass compressor options. \
  36. Pass options like -c hoist_vars=false,if_return=false. \
  37. Use -c with no argument to use the default compression options.")
  38. .describe("d", "Global definitions")
  39. .describe("e", "Embed everything in a big function, with a configurable parameter/argument list.")
  40. .describe("comments", "Preserve copyright comments in the output. \
  41. By default this works like Google Closure, keeping JSDoc-style comments that contain \"@license\" or \"@preserve\". \
  42. You can optionally pass one of the following arguments to this flag:\n\
  43. - \"all\" to keep all comments\n\
  44. - a valid JS regexp (needs to start with a slash) to keep only comments that match.\n\
  45. \
  46. Note that currently not *all* comments can be kept when compression is on, \
  47. because of dead code removal or cascading statements into sequences.")
  48. .describe("preamble", "Preamble to prepend to the output. You can use this to insert a \
  49. comment, for example for licensing information. This will not be \
  50. parsed, but the source map will adjust for its presence.")
  51. .describe("stats", "Display operations run time on STDERR.")
  52. .describe("acorn", "Use Acorn for parsing.")
  53. .describe("spidermonkey", "Assume input files are SpiderMonkey AST format (as JSON).")
  54. .describe("self", "Build itself (UglifyJS2) as a library (implies --wrap=UglifyJS --export-all)")
  55. .describe("wrap", "Embed everything in a big function, making the “exports” and “global” variables available. \
  56. You need to pass an argument to this option to specify the name that your module will take when included in, say, a browser.")
  57. .describe("export-all", "Only used when --wrap, this tells UglifyJS to add code to automatically export all globals.")
  58. .describe("lint", "Display some scope warnings")
  59. .describe("v", "Verbose")
  60. .describe("V", "Print version number and exit.")
  61. .describe("noerr", "Don't throw an error for unknown options in -c, -b or -m.")
  62. .describe("bare-returns", "Allow return outside of functions. Useful when minifying CommonJS modules.")
  63. .describe("keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.")
  64. .describe("quotes", "Quote style (0 - auto, 1 - single, 2 - double, 3 - original)")
  65. .describe("reserved-file", "File containing reserved names")
  66. .describe("reserve-domprops", "Make (most?) DOM properties reserved for --mangle-props")
  67. .describe("mangle-props", "Mangle property names")
  68. .describe("mangle-regex", "Only mangle property names matching the regex")
  69. .describe("name-cache", "File to hold mangled names mappings")
  70. .alias("p", "prefix")
  71. .alias("o", "output")
  72. .alias("v", "verbose")
  73. .alias("b", "beautify")
  74. .alias("m", "mangle")
  75. .alias("c", "compress")
  76. .alias("d", "define")
  77. .alias("r", "reserved")
  78. .alias("V", "version")
  79. .alias("e", "enclose")
  80. .alias("q", "quotes")
  81. .string("source-map")
  82. .string("source-map-root")
  83. .string("source-map-url")
  84. .string("b")
  85. .string("beautify")
  86. .string("m")
  87. .string("mangle")
  88. .string("c")
  89. .string("compress")
  90. .string("d")
  91. .string("define")
  92. .string("e")
  93. .string("enclose")
  94. .string("comments")
  95. .string("wrap")
  96. .string("p")
  97. .string("prefix")
  98. .string("name-cache")
  99. .array("reserved-file")
  100. .boolean("expr")
  101. .boolean("source-map-include-sources")
  102. .boolean("screw-ie8")
  103. .boolean("export-all")
  104. .boolean("self")
  105. .boolean("v")
  106. .boolean("verbose")
  107. .boolean("stats")
  108. .boolean("acorn")
  109. .boolean("spidermonkey")
  110. .boolean("lint")
  111. .boolean("V")
  112. .boolean("version")
  113. .boolean("noerr")
  114. .boolean("bare-returns")
  115. .boolean("keep-fnames")
  116. .boolean("mangle-props")
  117. .boolean("reserve-domprops")
  118. .wrap(80)
  119. .argv
  120. ;
  121. normalize(ARGS);
  122. if (ARGS.noerr) {
  123. UglifyJS.DefaultsError.croak = function(msg, defs) {
  124. print_error("WARN: " + msg);
  125. };
  126. }
  127. if (ARGS.version || ARGS.V) {
  128. var json = require("../package.json");
  129. print(json.name + ' ' + json.version);
  130. process.exit(0);
  131. }
  132. if (ARGS.ast_help) {
  133. var desc = UglifyJS.describe_ast();
  134. print(typeof desc == "string" ? desc : JSON.stringify(desc, null, 2));
  135. process.exit(0);
  136. }
  137. if (ARGS.h || ARGS.help) {
  138. print(yargs.help());
  139. process.exit(0);
  140. }
  141. if (ARGS.acorn) {
  142. acorn = require("acorn");
  143. }
  144. var COMPRESS = getOptions("c", true);
  145. var MANGLE = getOptions("m", true);
  146. var BEAUTIFY = getOptions("b", true);
  147. var RESERVED = null;
  148. if (ARGS.reserved_file) ARGS.reserved_file.forEach(function(filename){
  149. RESERVED = UglifyJS.readReservedFile(filename, RESERVED);
  150. });
  151. if (ARGS.reserve_domprops) {
  152. RESERVED = UglifyJS.readDefaultReservedFile(RESERVED);
  153. }
  154. if (ARGS.d) {
  155. if (COMPRESS) COMPRESS.global_defs = getOptions("d");
  156. }
  157. if (ARGS.r) {
  158. if (MANGLE) MANGLE.except = ARGS.r.replace(/^\s+|\s+$/g).split(/\s*,+\s*/);
  159. }
  160. if (RESERVED && MANGLE) {
  161. if (!MANGLE.except) MANGLE.except = RESERVED.vars;
  162. else MANGLE.except = MANGLE.except.concat(RESERVED.vars);
  163. }
  164. function readNameCache(key) {
  165. return UglifyJS.readNameCache(ARGS.name_cache, key);
  166. }
  167. function writeNameCache(key, cache) {
  168. return UglifyJS.writeNameCache(ARGS.name_cache, key, cache);
  169. }
  170. function extractRegex(str) {
  171. if (/^\/.*\/[a-zA-Z]*$/.test(str)) {
  172. var regex_pos = str.lastIndexOf("/");
  173. return new RegExp(str.substr(1, regex_pos - 1), str.substr(regex_pos + 1));
  174. } else {
  175. throw new Error("Invalid regular expression: " + str);
  176. }
  177. }
  178. if (ARGS.quotes === true) {
  179. ARGS.quotes = 3;
  180. }
  181. var OUTPUT_OPTIONS = {
  182. beautify : BEAUTIFY ? true : false,
  183. preamble : ARGS.preamble || null,
  184. quote_style : ARGS.quotes != null ? ARGS.quotes : 0
  185. };
  186. if (ARGS.screw_ie8) {
  187. if (COMPRESS) COMPRESS.screw_ie8 = true;
  188. if (MANGLE) MANGLE.screw_ie8 = true;
  189. OUTPUT_OPTIONS.screw_ie8 = true;
  190. }
  191. if (ARGS.keep_fnames) {
  192. if (COMPRESS) COMPRESS.keep_fnames = true;
  193. if (MANGLE) MANGLE.keep_fnames = true;
  194. }
  195. if (BEAUTIFY)
  196. UglifyJS.merge(OUTPUT_OPTIONS, BEAUTIFY);
  197. if (ARGS.comments != null) {
  198. if (/^\/.*\/[a-zA-Z]*$/.test(ARGS.comments)) {
  199. try {
  200. OUTPUT_OPTIONS.comments = extractRegex(ARGS.comments);
  201. } catch (e) {
  202. print_error("ERROR: Invalid --comments: " + e.message);
  203. }
  204. } else if (ARGS.comments == "all") {
  205. OUTPUT_OPTIONS.comments = true;
  206. } else {
  207. OUTPUT_OPTIONS.comments = function(node, comment) {
  208. var text = comment.value;
  209. var type = comment.type;
  210. if (type == "comment2") {
  211. // multiline comment
  212. return /@preserve|@license|@cc_on/i.test(text);
  213. }
  214. }
  215. }
  216. }
  217. var files = ARGS._.slice();
  218. if (ARGS.self) {
  219. if (files.length > 0) {
  220. print_error("WARN: Ignoring input files since --self was passed");
  221. }
  222. files = UglifyJS.FILES;
  223. if (!ARGS.wrap) ARGS.wrap = "UglifyJS";
  224. ARGS.export_all = true;
  225. }
  226. var ORIG_MAP = ARGS.in_source_map;
  227. if (ORIG_MAP) {
  228. ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP));
  229. if (files.length == 0) {
  230. print_error("INFO: Using file from the input source map: " + ORIG_MAP.file);
  231. files = [ ORIG_MAP.file ];
  232. }
  233. if (ARGS.source_map_root == null) {
  234. ARGS.source_map_root = ORIG_MAP.sourceRoot;
  235. }
  236. }
  237. if (files.length == 0) {
  238. files = [ "-" ];
  239. }
  240. if (files.indexOf("-") >= 0 && ARGS.source_map) {
  241. print_error("ERROR: Source map doesn't work with input from STDIN");
  242. process.exit(1);
  243. }
  244. if (files.filter(function(el){ return el == "-" }).length > 1) {
  245. print_error("ERROR: Can read a single file from STDIN (two or more dashes specified)");
  246. process.exit(1);
  247. }
  248. var STATS = {};
  249. var OUTPUT_FILE = ARGS.o;
  250. var TOPLEVEL = null;
  251. var P_RELATIVE = ARGS.p && ARGS.p == "relative";
  252. var SOURCES_CONTENT = {};
  253. var SOURCE_MAP = ARGS.source_map ? UglifyJS.SourceMap({
  254. file: P_RELATIVE ? path.relative(path.dirname(ARGS.source_map), OUTPUT_FILE) : OUTPUT_FILE,
  255. root: ARGS.source_map_root,
  256. orig: ORIG_MAP,
  257. }) : null;
  258. OUTPUT_OPTIONS.source_map = SOURCE_MAP;
  259. try {
  260. var output = UglifyJS.OutputStream(OUTPUT_OPTIONS);
  261. var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS);
  262. } catch(ex) {
  263. if (ex instanceof UglifyJS.DefaultsError) {
  264. print_error(ex.msg);
  265. print_error("Supported options:");
  266. print_error(sys.inspect(ex.defs));
  267. process.exit(1);
  268. }
  269. }
  270. async.eachLimit(files, 1, function (file, cb) {
  271. read_whole_file(file, function (err, code) {
  272. if (err) {
  273. print_error("ERROR: can't read file: " + file);
  274. process.exit(1);
  275. }
  276. if (ARGS.p != null) {
  277. if (P_RELATIVE) {
  278. file = path.relative(path.dirname(ARGS.source_map), file).replace(/\\/g, '/');
  279. } else {
  280. var p = parseInt(ARGS.p, 10);
  281. if (!isNaN(p)) {
  282. file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/");
  283. }
  284. }
  285. }
  286. SOURCES_CONTENT[file] = code;
  287. time_it("parse", function(){
  288. if (ARGS.spidermonkey) {
  289. var program = JSON.parse(code);
  290. if (!TOPLEVEL) TOPLEVEL = program;
  291. else TOPLEVEL.body = TOPLEVEL.body.concat(program.body);
  292. }
  293. else if (ARGS.acorn) {
  294. TOPLEVEL = acorn.parse(code, {
  295. locations : true,
  296. sourceFile : file,
  297. program : TOPLEVEL
  298. });
  299. }
  300. else {
  301. try {
  302. TOPLEVEL = UglifyJS.parse(code, {
  303. filename : file,
  304. toplevel : TOPLEVEL,
  305. expression : ARGS.expr,
  306. bare_returns : ARGS.bare_returns,
  307. });
  308. } catch(ex) {
  309. if (ex instanceof UglifyJS.JS_Parse_Error) {
  310. print_error("Parse error at " + file + ":" + ex.line + "," + ex.col);
  311. print_error(ex.message);
  312. print_error(ex.stack);
  313. process.exit(1);
  314. }
  315. throw ex;
  316. }
  317. };
  318. });
  319. cb();
  320. });
  321. }, function () {
  322. if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){
  323. TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL);
  324. });
  325. if (ARGS.wrap != null) {
  326. TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all);
  327. }
  328. if (ARGS.enclose != null) {
  329. var arg_parameter_list = ARGS.enclose;
  330. if (arg_parameter_list === true) {
  331. arg_parameter_list = [];
  332. }
  333. else if (!(arg_parameter_list instanceof Array)) {
  334. arg_parameter_list = [arg_parameter_list];
  335. }
  336. TOPLEVEL = TOPLEVEL.wrap_enclose(arg_parameter_list);
  337. }
  338. if (ARGS.mangle_props || ARGS.name_cache) (function(){
  339. var reserved = RESERVED ? RESERVED.props : null;
  340. var cache = readNameCache("props");
  341. var regex;
  342. try {
  343. regex = ARGS.mangle_regex ? extractRegex(ARGS.mangle_regex) : null;
  344. } catch (e) {
  345. print_error("ERROR: Invalid --mangle-regex: " + e.message);
  346. process.exit(1);
  347. }
  348. TOPLEVEL = UglifyJS.mangle_properties(TOPLEVEL, {
  349. reserved : reserved,
  350. cache : cache,
  351. only_cache : !ARGS.mangle_props,
  352. regex : regex
  353. });
  354. writeNameCache("props", cache);
  355. })();
  356. var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint;
  357. var TL_CACHE = readNameCache("vars");
  358. if (SCOPE_IS_NEEDED) {
  359. time_it("scope", function(){
  360. TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8, cache: TL_CACHE });
  361. if (ARGS.lint) {
  362. TOPLEVEL.scope_warnings();
  363. }
  364. });
  365. }
  366. if (COMPRESS) {
  367. time_it("squeeze", function(){
  368. TOPLEVEL = TOPLEVEL.transform(compressor);
  369. });
  370. }
  371. if (SCOPE_IS_NEEDED) {
  372. time_it("scope", function(){
  373. TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8, cache: TL_CACHE });
  374. if (MANGLE && !TL_CACHE) {
  375. TOPLEVEL.compute_char_frequency(MANGLE);
  376. }
  377. });
  378. }
  379. if (MANGLE) time_it("mangle", function(){
  380. MANGLE.cache = TL_CACHE;
  381. TOPLEVEL.mangle_names(MANGLE);
  382. });
  383. writeNameCache("vars", TL_CACHE);
  384. if (ARGS.source_map_include_sources) {
  385. for (var file in SOURCES_CONTENT) {
  386. if (SOURCES_CONTENT.hasOwnProperty(file)) {
  387. SOURCE_MAP.get().setSourceContent(file, SOURCES_CONTENT[file]);
  388. }
  389. }
  390. }
  391. time_it("generate", function(){
  392. TOPLEVEL.print(output);
  393. });
  394. output = output.get();
  395. if (SOURCE_MAP) {
  396. fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8");
  397. var source_map_url = ARGS.source_map_url || (
  398. P_RELATIVE
  399. ? path.relative(path.dirname(OUTPUT_FILE), ARGS.source_map)
  400. : ARGS.source_map
  401. );
  402. output += "\n//# sourceMappingURL=" + source_map_url;
  403. }
  404. if (OUTPUT_FILE) {
  405. fs.writeFileSync(OUTPUT_FILE, output, "utf8");
  406. } else {
  407. print(output);
  408. }
  409. if (ARGS.stats) {
  410. print_error(UglifyJS.string_template("Timing information (compressed {count} files):", {
  411. count: files.length
  412. }));
  413. for (var i in STATS) if (STATS.hasOwnProperty(i)) {
  414. print_error(UglifyJS.string_template("- {name}: {time}s", {
  415. name: i,
  416. time: (STATS[i] / 1000).toFixed(3)
  417. }));
  418. }
  419. }
  420. });
  421. /* -----[ functions ]----- */
  422. function normalize(o) {
  423. for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) {
  424. o[i.replace(/-/g, "_")] = o[i];
  425. delete o[i];
  426. }
  427. }
  428. function getOptions(x, constants) {
  429. x = ARGS[x];
  430. if (x == null) return null;
  431. var ret = {};
  432. if (x !== "") {
  433. var ast;
  434. try {
  435. ast = UglifyJS.parse(x, { expression: true });
  436. } catch(ex) {
  437. if (ex instanceof UglifyJS.JS_Parse_Error) {
  438. print_error("Error parsing arguments in: " + x);
  439. process.exit(1);
  440. }
  441. }
  442. ast.walk(new UglifyJS.TreeWalker(function(node){
  443. if (node instanceof UglifyJS.AST_Seq) return; // descend
  444. if (node instanceof UglifyJS.AST_Assign) {
  445. var name = node.left.print_to_string({ beautify: false }).replace(/-/g, "_");
  446. var value = node.right;
  447. if (constants)
  448. value = new Function("return (" + value.print_to_string() + ")")();
  449. ret[name] = value;
  450. return true; // no descend
  451. }
  452. if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_Binary) {
  453. var name = node.print_to_string({ beautify: false }).replace(/-/g, "_");
  454. ret[name] = true;
  455. return true; // no descend
  456. }
  457. print_error(node.TYPE)
  458. print_error("Error parsing arguments in: " + x);
  459. process.exit(1);
  460. }));
  461. }
  462. return ret;
  463. }
  464. function read_whole_file(filename, cb) {
  465. if (filename == "-") {
  466. var chunks = [];
  467. process.stdin.setEncoding('utf-8');
  468. process.stdin.on('data', function (chunk) {
  469. chunks.push(chunk);
  470. }).on('end', function () {
  471. cb(null, chunks.join(""));
  472. });
  473. process.openStdin();
  474. } else {
  475. fs.readFile(filename, "utf-8", cb);
  476. }
  477. }
  478. function time_it(name, cont) {
  479. var t1 = new Date().getTime();
  480. var ret = cont();
  481. if (ARGS.stats) {
  482. var spent = new Date().getTime() - t1;
  483. if (STATS[name]) STATS[name] += spent;
  484. else STATS[name] = spent;
  485. }
  486. return ret;
  487. }
  488. function print_error(msg) {
  489. console.error("%s", msg);
  490. }
  491. function print(txt) {
  492. console.log("%s", txt);
  493. }