diff --git a/packages/babel-generator/src/printer.ts b/packages/babel-generator/src/printer.ts index 9acbe5dd4bee..48e28b31cf1e 100644 --- a/packages/babel-generator/src/printer.ts +++ b/packages/babel-generator/src/printer.ts @@ -950,9 +950,9 @@ class Printer { for (let i = 0; i < len; i++) { const comment = comments[i]; - if (hasLoc && "loc" in comment && !this._printedComments.has(comment)) { - const commentStartLine = comment.loc?.start.line; - const commentEndLine = comment.loc?.end.line; + if (hasLoc && comment.loc && !this._printedComments.has(comment)) { + const commentStartLine = comment.loc.start.line; + const commentEndLine = comment.loc.end.line; if (type === COMMENT_TYPE.LEADING) { let offset = 0; if (i === 0) { diff --git a/packages/babel-generator/test/index.js b/packages/babel-generator/test/index.js index f965e149d696..d5117a452555 100644 --- a/packages/babel-generator/test/index.js +++ b/packages/babel-generator/test/index.js @@ -472,6 +472,17 @@ describe("generation", function () { expect(generate(ast).code).toBe("/*#__PURE__*/a();\n/*#__PURE__*/b();"); }); + + it("comments with null or undefined loc", () => { + const code = "/*#__PURE__*/ /*#__PURE__*/"; + + const ast = parse(code); + + ast.comments[0].loc = null; + ast.comments[1].loc = undefined; + + expect(generate(ast).code).toBe("/*#__PURE__*/\n/*#__PURE__*/"); + }); }); describe("programmatic generation", function () {