Export anonymous functions in 2 steps, declare as variable and then assign to exports. (#39820)

* Preserve the variable name when exporting an arrow or anonymous function
 This allows the browser or node to properly name the (arrow) function

* Updated tests to reflect previous change

* Remove duplicated comment

* Transforms variable.initializer using moduleExpressionElementVisitor

* PR feedback: rbuckton
 - Use isArrowFunction and isFunctionExpression

* PR feedback: rbuckton
- Consider ClassExpresion, they can also be named based on the
  variable.
This commit is contained in:
Josejulio Martínez
2020-08-07 19:16:03 -05:00
committed by GitHub
parent 3328fdb2d8
commit 668bbc64ff
36 changed files with 111 additions and 42 deletions

View File

@@ -1195,6 +1195,7 @@ namespace ts {
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
let modifiers: NodeArray<Modifier> | undefined;
let removeCommentsOnExpressions = false;
// If we're exporting these variables, then these just become assignments to 'exports.x'.
for (const variable of node.declarationList.declarations) {
@@ -1206,7 +1207,31 @@ namespace ts {
variables = append(variables, variable);
}
else if (variable.initializer) {
expressions = append(expressions, transformInitializedVariable(variable as InitializedVariableDeclaration));
if (!isBindingPattern(variable.name) && (isArrowFunction(variable.initializer) || isFunctionExpression(variable.initializer) || isClassExpression(variable.initializer))) {
const expression = factory.createAssignment(
setTextRange(
factory.createPropertyAccessExpression(
factory.createIdentifier("exports"),
variable.name
),
/*location*/ variable.name
),
factory.createIdentifier(getTextOfIdentifierOrLiteral(variable.name))
);
const updatedVariable = factory.createVariableDeclaration(
variable.name,
variable.exclamationToken,
variable.type,
visitNode(variable.initializer, moduleExpressionElementVisitor)
);
variables = append(variables, updatedVariable);
expressions = append(expressions, expression);
removeCommentsOnExpressions = true;
}
else {
expressions = append(expressions, transformInitializedVariable(variable as InitializedVariableDeclaration));
}
}
}
@@ -1215,7 +1240,11 @@ namespace ts {
}
if (expressions) {
statements = append(statements, setOriginalNode(setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node));
const statement = setOriginalNode(setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node);
if (removeCommentsOnExpressions) {
removeAllComments(statement);
}
statements = append(statements, statement);
}
}
else {