diff --git a/packages/babel-generator/src/printer.ts b/packages/babel-generator/src/printer.ts index 1a0c6e2a7af0..f55ec31cfb93 100644 --- a/packages/babel-generator/src/printer.ts +++ b/packages/babel-generator/src/printer.ts @@ -2,7 +2,7 @@ import Buffer from "./buffer"; import type { Loc } from "./buffer"; import * as n from "./node"; import type * as t from "@babel/types"; -import { isProperty, isFunction, isStatement } from "@babel/types"; +import { isProperty, isFunction, isStatement, isLVal } from "@babel/types"; import type { RecordAndTuplePluginOptions, PipelineOperatorPluginOptions, @@ -1011,14 +1011,20 @@ class Printer { } else { hasLoc = false; - if (len === 1 && type === COMMENT_TYPE.LEADING) { - this._printComment( - comment, - (!isStatement(node) && !isProperty(node)) || - isFunction(parent, { body: node }) - ? COMMENT_SKIP_NEWLINE.SKIP_ALL - : COMMENT_SKIP_NEWLINE.DEFAULT, - ); + if (len === 1) { + if (type === COMMENT_TYPE.LEADING) { + this._printComment( + comment, + (!isStatement(node) && !isProperty(node)) || + isFunction(parent, { body: node }) + ? COMMENT_SKIP_NEWLINE.SKIP_ALL + : COMMENT_SKIP_NEWLINE.DEFAULT, + ); + } else if (type === COMMENT_TYPE.TRAILING && isLVal(node)) { + this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL); + } else { + this._printComment(comment, COMMENT_SKIP_NEWLINE.DEFAULT); + } } else if ( type === COMMENT_TYPE.INNER && !(node.type === "ObjectExpression" && node.properties.length > 1) && diff --git a/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/class-prop-values/output.js b/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/class-prop-values/output.js index a993e304e28e..bb9997322925 100644 --- a/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/class-prop-values/output.js +++ b/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/class-prop-values/output.js @@ -1,4 +1,5 @@ class X { foo = 2; - bar /*: number*/ = 3; /*:: baz: ?string*/ + bar /*: number*/ = 3; + /*:: baz: ?string*/ } diff --git a/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/type-cast/output.js b/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/type-cast/output.js index 1b2c5f2b1fca..adfbff51872f 100644 --- a/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/type-cast/output.js +++ b/packages/babel-plugin-transform-flow-comments/test/fixtures/flow-comments/type-cast/output.js @@ -1,2 +1,4 @@ var a = (y /*: any*/); -var a = ((y /*: foo*/) /*: any*/); +var a = ((y /*: foo*/) +/*: any*/ +);