Skip to content

Commit 2ec06ca

Browse files
feat(javascript): fold optional calls of a nullish const in the minifier
terser reads a variable as nullish only when its fixed value is stored as a node, so a `const d = void 0` read more than once keeps every `d?.(…)`. Refs terser/terser#1400
1 parent cf97e07 commit 2ec06ca

3 files changed

Lines changed: 16 additions & 2 deletions

File tree

‎.changeset/047-javascript-minifier-unwrap-iife.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": patch
33
---
44

5-
Unwrap IIFEs, fold built-in calls, drop unused built-ins and write long string arrays as one split string when minifying JS.
5+
Unwrap IIFEs, fold built-in calls and optional calls of nullish constants, drop unused built-ins and write long string arrays as one split string when minifying JS.

‎lib/javascript/syntax-printer.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37622,7 +37622,15 @@ const createCompressHelpers = (modules) => {
3762237622
const undefinedValue = isUndefined(node, compressor);
3762337623
if (undefinedValue) return undefinedValue;
3762437624
if (!isSymbolRefNode(node)) return false;
37625-
const fixed = node.definition.fixed;
37625+
let fixed = node.definition.fixed;
37626+
// terser reads only a value stored as a node, not one read lazily.
37627+
if (
37628+
!isSyntaxNode(fixed) &&
37629+
modules.improvements !== undefined &&
37630+
modules.improvements.enabled
37631+
) {
37632+
fixed = ast.fixedValue(node);
37633+
}
3762637634
return (
3762737635
isSyntaxNode(fixed) && isNullish(/** @type {Node} */ (fixed), compressor)
3762837636
);

‎test/unitCases/syntax-printer.unittest.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,12 @@ const stringArray = (length, string = (index) => `w${index}`) =>
233233

234234
/** @type {[string, string, import("terser").MinifyOptions, string?][]} */
235235
const IMPROVED_CASES = [
236+
[
237+
"optional calls of a `const` known `undefined`, read too often to inline",
238+
"function f(g) { const d = void 0; d?.(g()); d?.(g()); d?.(g()); return [d?.x.y, d ?? 1]; } console.log(f(() => console.log(\"called\")));",
239+
{ compress: {}, mangle: false },
240+
"function f(g){return[void 0,1]}console.log(f(()=>console.log(\"called\")));"
241+
],
236242
[
237243
"an assignment to a `let` folded into the first read of it",
238244
"function f(a) { let x, y; x = a * 2; y = g(x); return [x, y]; } function g(v) { return v + 1; } console.log(f(3));",

0 commit comments

Comments
 (0)