diff --git a/crates/oxc_formatter/src/write/program.rs b/crates/oxc_formatter/src/write/program.rs index bb82f3435c4e5..8086f10423099 100644 --- a/crates/oxc_formatter/src/write/program.rs +++ b/crates/oxc_formatter/src/write/program.rs @@ -113,7 +113,15 @@ impl<'a> Format<'a> for AstNode<'a, Vec<'a, Directive<'a>>> { //``` // so we should keep an extra empty line after JsDirectiveList - let need_extra_empty_line = f.source_text().lines_after(last_directive.span.end) > 1; + let end = if let Some(last_printed_comment) = f.comments().printed_comments().last() + && last_printed_comment.span.end > last_directive.span.end + { + last_printed_comment.span.end + } else { + last_directive.span.end + }; + + let need_extra_empty_line = f.source_text().lines_after(end) > 1; write!(f, if need_extra_empty_line { empty_line() } else { hard_line_break() }) } } diff --git a/crates/oxc_formatter/tests/fixtures/js/comments/directive.js b/crates/oxc_formatter/tests/fixtures/js/comments/directive.js new file mode 100644 index 0000000000000..d49de51b07c6d --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/js/comments/directive.js @@ -0,0 +1,4 @@ +"use strict"; + +// comment +(() => {}); \ No newline at end of file diff --git a/crates/oxc_formatter/tests/fixtures/js/comments/directive.js.snap b/crates/oxc_formatter/tests/fixtures/js/comments/directive.js.snap new file mode 100644 index 0000000000000..60c94cc7c62d4 --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/js/comments/directive.js.snap @@ -0,0 +1,15 @@ +--- +source: crates/oxc_formatter/tests/fixtures/mod.rs +--- +==================== Input ==================== +"use strict"; + +// comment +(() => {}); +==================== Output ==================== +"use strict"; + +// comment +() => {}; + +===================== End =====================