From 5ab2a21b02a71d5ece07758efa91db36bb6c1e94 Mon Sep 17 00:00:00 2001 From: Lauri Rooden Date: Mon, 13 Nov 2023 13:17:56 +0200 Subject: [PATCH] add support to specify mangled name (#5815) --- README.md | 9 +++++++++ lib/scope.js | 8 +++++++- test/compress/keep_fargs.js | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e86f33d0589..ffd8344e84b 100644 --- a/README.md +++ b/README.md @@ -1029,6 +1029,15 @@ discarded by the compressor as not referenced. The safest comments where to place copyright information (or other info that needs to be kept in the output) are comments attached to toplevel nodes. +### Specify preferred mangled name in comment annotations + +`/*@mangleTo:X*/` or `/*@mangleTo:X*/` comments allow you to choose the name. + +```javascript +(function(one /*#mangleTo:H*/, two /*#mangleTo:i*/) { /*..*/ })(1, 2); +// results (function(H,i){ /*..*/ )(1,2); +``` + ### The `unsafe` `compress` option It enables some transformations that *might* break code logic in certain diff --git a/lib/scope.js b/lib/scope.js index 359c4f97da3..2d07e27d903 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -565,7 +565,13 @@ function next_mangled_name(def, options) { scopes.push(scope); } while (scope = scope.parent_scope); }); - var name; + var comment = def.orig[0].start.comments_after[0]?.value; + var preferred_name = comment && /[@#]mangleTo:(.*)/.exec(comment); + var name = preferred_name && preferred_name[1]; + if (name && !names.has(name)) { + in_use.set(name, true); + return name; + } for (var i = 0; i < holes.length; i++) { name = base54(holes[i]); if (names.has(name)) continue; diff --git a/test/compress/keep_fargs.js b/test/compress/keep_fargs.js index a8e34cca580..900ca83b4d8 100644 --- a/test/compress/keep_fargs.js +++ b/test/compress/keep_fargs.js @@ -965,6 +965,20 @@ function_name_mangle: { expect_stdout: "function" } +function_name_mangle_from_preferred_comment: { + options = { + keep_fargs: false, + } + mangle = {} + input: { + (function(one /*#mangleTo:W*/, two) { + console.log(one, two); + })(1, 2); + } + expect_exact: "(function(W,o){console.log(W,o)})(1,2);" + expect_stdout: "1 2" +} + function_name_mangle_ie8: { options = { keep_fargs: false,