diff --git a/src/comments.js b/src/comments.js index ee56ad231db1..9681affdf3f0 100644 --- a/src/comments.js +++ b/src/comments.js @@ -192,6 +192,12 @@ function attach(comments, ast, text) { comment ) || handleTryStatementComments(enclosingNode, followingNode, comment) || + handleClassComments( + enclosingNode, + precedingNode, + followingNode, + comment + ) || handleImportSpecifierComments(enclosingNode, comment) || handleObjectPropertyComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || @@ -246,6 +252,12 @@ function attach(comments, ast, text) { followingNode, comment ) || + handleClassComments( + enclosingNode, + precedingNode, + followingNode, + comment + ) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || @@ -551,6 +563,32 @@ function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) { return false; } +function handleClassComments( + enclosingNode, + precedingNode, + followingNode, + comment +) { + if ( + enclosingNode && + (enclosingNode.type === "ClassDeclaration" || + enclosingNode.type === "ClassExpression") && + (enclosingNode.decorators && enclosingNode.decorators.length > 0) && + !(followingNode && followingNode.type === "Decorator") + ) { + if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) { + addLeadingComment(enclosingNode, comment); + } else { + addTrailingComment( + enclosingNode.decorators[enclosingNode.decorators.length - 1], + comment + ); + } + return true; + } + return false; +} + function handleMethodNameComments(text, enclosingNode, precedingNode, comment) { // This is only needed for estree parsers (flow, typescript) to attach // after a method name: diff --git a/tests/decorators/__snapshots__/jsfmt.spec.js.snap b/tests/decorators/__snapshots__/jsfmt.spec.js.snap index 95c70dee42bc..7079563c8449 100644 --- a/tests/decorators/__snapshots__/jsfmt.spec.js.snap +++ b/tests/decorators/__snapshots__/jsfmt.spec.js.snap @@ -25,6 +25,13 @@ class X { ], }) export class AppModule {} + +// A +@Foo() +// B +@Bar() +// C +export class Bar{} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var x = 100; @@ -48,6 +55,13 @@ class X {} }) export class AppModule {} +// A +@Foo() +// B +@Bar() +// C +export class Bar {} + `; exports[`methods.js 1`] = ` diff --git a/tests/decorators/comments.js b/tests/decorators/comments.js index 9b5bf8ce67f7..8aa68576c591 100644 --- a/tests/decorators/comments.js +++ b/tests/decorators/comments.js @@ -22,3 +22,10 @@ class X { ], }) export class AppModule {} + +// A +@Foo() +// B +@Bar() +// C +export class Bar{}