(literal: o.Expression, forceShared?: boolean)
| 95 | constructor(private readonly isClosureCompilerEnabled: boolean = false) {} |
| 96 | |
| 97 | getConstLiteral(literal: o.Expression, forceShared?: boolean): o.Expression { |
| 98 | if ( |
| 99 | (literal instanceof o.LiteralExpr && !isLongStringLiteral(literal)) || |
| 100 | literal instanceof FixupExpression |
| 101 | ) { |
| 102 | // Do no put simple literals into the constant pool or try to produce a constant for a |
| 103 | // reference to a constant. |
| 104 | return literal; |
| 105 | } |
| 106 | const key = GenericKeyFn.INSTANCE.keyOf(literal); |
| 107 | let fixup = this.literals.get(key); |
| 108 | let newValue = false; |
| 109 | if (!fixup) { |
| 110 | fixup = new FixupExpression(literal); |
| 111 | this.literals.set(key, fixup); |
| 112 | newValue = true; |
| 113 | } |
| 114 | |
| 115 | if ((!newValue && !fixup.shared) || (newValue && forceShared)) { |
| 116 | // Replace the expression with a variable |
| 117 | const name = this.freshName(); |
| 118 | let value: o.Expression; |
| 119 | let usage: o.Expression; |
| 120 | if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) { |
| 121 | // For string literals, Closure will **always** inline the string at |
| 122 | // **all** usages, duplicating it each time. For large strings, this |
| 123 | // unnecessarily bloats bundle size. To work around this restriction, we |
| 124 | // wrap the string in a function, and call that function for each usage. |
| 125 | // This tricks Closure into using inline logic for functions instead of |
| 126 | // string literals. Function calls are only inlined if the body is small |
| 127 | // enough to be worth it. By doing this, very large strings will be |
| 128 | // shared across multiple usages, rather than duplicating the string at |
| 129 | // each usage site. |
| 130 | // |
| 131 | // const myStr = function() { return "very very very long string"; }; |
| 132 | // const usage1 = myStr(); |
| 133 | // const usage2 = myStr(); |
| 134 | value = new o.FunctionExpr( |
| 135 | [], // Params. |
| 136 | [ |
| 137 | // Statements. |
| 138 | new o.ReturnStatement(literal), |
| 139 | ], |
| 140 | ); |
| 141 | usage = o.variable(name).callFn([]); |
| 142 | } else { |
| 143 | // Just declare and use the variable directly, without a function call |
| 144 | // indirection. This saves a few bytes and avoids an unnecessary call. |
| 145 | value = literal; |
| 146 | usage = o.variable(name); |
| 147 | } |
| 148 | |
| 149 | this.statements.push( |
| 150 | new o.DeclareVarStmt(name, value, o.INFERRED_TYPE, o.StmtModifier.Final), |
| 151 | ); |
| 152 | fixup.fixup(usage); |
| 153 | } |
| 154 |
no test coverage detected