'printer.printFile prints empty string
I am using the compiler API to create Typescript code. After assigning const printer = createPrinter(), I can use printer.printNode and printer.printList to print my AST. But for some reason, printer.printFile always prints empty strings.
const printer = createPrinter();
const sourceFile = createSourceFile(
'dummy.ts',
'',
ScriptTarget.ESNext,
false,
ScriptKind.TS
);
const classDeclaration = factory.createClassDeclaration(
undefined,
undefined,
'Foo',
undefined,
undefined,
[]
);
factory.updateSourceFile(sourceFile, factory.createNodeArray([classDeclaration]));
console.log(printer.printFile(sourceFile)); // '';
Why is printer.printFile always printing an empty string?
Solution 1:[1]
I'm not sure why but it looks like the factory.updateSourceFile returns the updated SourceFile.
const printer = createPrinter();
// const -> let
let sourceFile = createSourceFile(
'dummy.ts',
'',
ScriptTarget.ESNext,
false,
ScriptKind.TS
);
const classDeclaration = factory.createClassDeclaration(
undefined,
undefined,
'Foo',
undefined,
undefined,
[]
);
// assign the updated source file
sourceFile = factory.updateSourceFile(sourceFile, factory.createNodeArray([classDeclaration]));
console.log(printer.printFile(sourceFile));
// class Foo {
// }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bmdelacruz |
