You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过TypeScript Compiler API实现多行NamedImports?

实现多行命名导入的调整方案

TypeScript Compiler API 创建的 AST 节点本身并不包含换行、缩进这类格式化信息,最终代码的排版由 ts.Printer 实例的配置决定。你需要在打印 AST 节点时,指定对应的格式化选项来实现多行命名导入的效果。

具体调整步骤

  1. 配置打印机选项:创建 ts.Printer 时,设置 importClauseIndentation 为 ts.ImportClauseIndentation.Always,同时指定换行符和缩进规则。
  2. 使用配置好的打印机生成代码:将你创建的 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:50:26