如何通过TypeScript Compiler API实现多行NamedImports?
实现多行命名导入的调整方案
TypeScript Compiler API 创建的 AST 节点本身并不包含换行、缩进这类格式化信息,最终代码的排版由 ts.Printer 实例的配置决定。你需要在打印 AST 节点时,指定对应的格式化选项来实现多行命名导入的效果。
具体调整步骤
- 配置打印机选项:创建
ts.Printer时,设置importClauseIndentation为ts.ImportClauseIndentation.Always,同时指定换行符和缩进规则。 - 使用配置好的打印机生成代码:将你创建的
ImportDeclaration节点传入打印机的printNode方法。
修改后的完整代码示例
import * as ts from 'typescript'; // 假设你已有的 factory、node、uniqImports 等变量已定义 const importClause = ts.factory.createImportClause( Boolean(node.importClause?.isTypeOnly), node.importClause?.name, ts.factory.createNamedImports(uniqImports as ts.ImportSpecifier[]), ); const importProps: ts.ImportDeclaration = ts.factory.createImportDeclaration( node.decorators, node.modifiers, importClause, node.moduleSpecifier, node.assertClause, ); // 配置打印机 const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, importClauseIndentation: ts.ImportClauseIndentation.Always, indentSize: 4, // 根据你的需求设置缩进宽度 tabWidth: 4 }); // 生成格式化后的代码 const sourceFile = ts.createSourceFile( 'temp.ts', '', ts.ScriptTarget.Latest, false, ts.ScriptKind.TS ); const formattedCode = printer.printNode(ts.EmitHint.Unspecified, importProps, sourceFile); console.log(formattedCode);
关键配置说明
importClauseIndentation: ts.ImportClauseIndentation.Always:强制将命名导入的内容放在单独一行,并添加缩进。indentSize和tabWidth:控制缩进的宽度,确保每个导入项的缩进一致。newLine:指定换行符类型(LF 或 CRLF),保持代码换行风格统一。
这样配置后,生成的代码就会符合你期望的多行命名导入格式。
内容的提问来源于stack exchange,提问作者Maxim Zadorkin
相关产品推荐
相关产品推荐

