Skip to content

Commit

Permalink
improve
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxingbaoyu committed Oct 16, 2022
1 parent 6deee84 commit d5699e4
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/babel-generator/src/printer.ts
Expand Up @@ -1017,19 +1017,25 @@ class Printer {
hasLoc = false;

if (len === 1) {
const shouldSkipNewline =
let shouldSkipNewline = comment.loc
? comment.loc.start.line === comment.loc.end.line
: !comment.value.includes("\n");

shouldSkipNewline =
shouldSkipNewline &&
!isStatement(node) &&
!isClassBody(parent) &&
!isTSInterfaceBody(parent);

if (type === COMMENT_TYPE.LEADING) {
this._printComment(
comment,
shouldSkipNewline || isFunction(parent, { body: node })
(shouldSkipNewline && node.type !== "ObjectExpression") ||
isFunction(parent, { body: node })
? COMMENT_SKIP_NEWLINE.SKIP_ALL
: COMMENT_SKIP_NEWLINE.DEFAULT,
);
} else if (type === COMMENT_TYPE.TRAILING && shouldSkipNewline) {
} else if (shouldSkipNewline && type === COMMENT_TYPE.TRAILING) {
this._printComment(comment, COMMENT_SKIP_NEWLINE.SKIP_ALL);
} else {
this._printComment(comment, COMMENT_SKIP_NEWLINE.DEFAULT);
Expand Down
60 changes: 60 additions & 0 deletions packages/babel-generator/test/index.js
Expand Up @@ -573,6 +573,66 @@ describe("generation", function () {
}"
`);
});

it("comments without loc2", () => {
const ast = parse(
`
(function (_templateFactory) {
"use strict";
const template = (0, _templateFactory.createTemplateFactory)(
/*{{somevalue}}*/
{
"id": null,
"block": "[[[1,[34,0]]],[],false,[\\"somevalue\\"]]",
"moduleName": "(unknown template module)",
"isStrictMode": false
});
});
const template = (0, _templateFactory.createTemplateFactory)(
/*
{{somevalue}}
*/
{
"id": null,
"block": "[[[1,[34,0]]],[],false,[\\"somevalue\\"]]",
"moduleName": "(unknown template module)",
"isStrictMode": false
});
`,
{ sourceType: "module" },
);

for (const comment of ast.comments) {
comment.loc = undefined;
}

expect(generate(ast).code).toMatchInlineSnapshot(`
"(function (_templateFactory) {
\\"use strict\\";
const template = (0, _templateFactory.createTemplateFactory)(
/*{{somevalue}}*/
{
\\"id\\": null,
\\"block\\": \\"[[[1,[34,0]]],[],false,[\\\\\\"somevalue\\\\\\"]]\\",
\\"moduleName\\": \\"(unknown template module)\\",
\\"isStrictMode\\": false
});
});
const template = (0, _templateFactory.createTemplateFactory)(
/*
{{somevalue}}
*/
{
\\"id\\": null,
\\"block\\": \\"[[[1,[34,0]]],[],false,[\\\\\\"somevalue\\\\\\"]]\\",
\\"moduleName\\": \\"(unknown template module)\\",
\\"isStrictMode\\": false
});"
`);
});
});

describe("programmatic generation", function () {
Expand Down

0 comments on commit d5699e4

Please sign in to comment.