Don't emit duplicate triple-slash directives when using API to print a .d.ts

This commit is contained in:
Ron Buckton 2020-10-06 15:02:41 -07:00
parent 692502e99f
commit 14714bbace
2 changed files with 39 additions and 1 deletions

View file

@ -5135,7 +5135,12 @@ namespace ts {
hasWrittenComment = false;
if (isEmittedNode) {
forEachLeadingCommentToEmit(pos, emitLeadingComment);
if (pos === 0 && currentSourceFile?.isDeclarationFile) {
forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
}
else {
forEachLeadingCommentToEmit(pos, emitLeadingComment);
}
}
else if (pos === 0) {
// If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
@ -5156,6 +5161,12 @@ namespace ts {
}
}
function emitNonTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
if (!isTripleSlashComment(commentPos, commentEnd)) {
emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
}
}
function shouldWriteComment(text: string, pos: number) {
if (printerOptions.onlyPrintJsDocStyle) {
return (isJSDocLikeText(text, pos) || isPinnedComment(text, pos));

View file

@ -93,6 +93,33 @@ namespace ts {
});
});
describe("No duplicate ref directives when emiting .d.ts->.d.ts", () => {
it("without statements", () => {
const host = new fakes.CompilerHost(new vfs.FileSystem(true, {
files: {
"/test.d.ts": `/// <reference types="node" />\n/// <reference path="./src/test.d.ts />\n`
}
}));
const program = createProgram(["/test.d.ts"], { }, host);
const file = program.getSourceFile("/test.d.ts")!;
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed });
const output = printer.printFile(file);
assert.equal(output.split(/\r?\n/g).length, 3);
});
it("with statements", () => {
const host = new fakes.CompilerHost(new vfs.FileSystem(true, {
files: {
"/test.d.ts": `/// <reference types="node" />\n/// <reference path="./src/test.d.ts />\nvar a: number;\n`
}
}));
const program = createProgram(["/test.d.ts"], { }, host);
const file = program.getSourceFile("/test.d.ts")!;
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed });
const output = printer.printFile(file);
assert.equal(output.split(/\r?\n/g).length, 4);
});
});
describe("printBundle", () => {
const printsCorrectly = makePrintsCorrectly("printsBundleCorrectly");
let bundle: Bundle;