importLines

tcmts.cli.main.importLines · #3qzeu7zx · term · runs anywhere

An import declaration as one import per name it binds (for grouping), each with the name.

import { isTypeOnlyImport } from "#codebase/tcmts/core/ts";
import { isNamedImports, isNamespaceImport as ts_isNamespaceImport } from "typescript/ast";
import type { ImportDeclaration } from "typescript/ast";

export function importLines(st: ImportDeclaration, text: string): { local: string; line: string }[] {
  const c = st.importClause;
  if (!c) return [];
  const from = text.slice(st.moduleSpecifier.getStart(), st.moduleSpecifier.end);
  const type = isTypeOnlyImport(c) ? "type " : "";
  const b = c.namedBindings;
  return [
    ...(c.name ? [{ local: c.name.text, line: `import ${type}${c.name.text} from ${from};` }] : []),
    ...(b && ts_isNamespaceImport(b) ? [{ local: b.name.text, line: `import ${type}* as ${b.name.text} from ${from};` }] : []),
    ...(b && isNamedImports(b)
      ? b.elements.map((e) => ({ local: e.name.text, line: `import ${type || (e.isTypeOnly ? "type " : "")}{ ${e.propertyName ? `${text.slice(e.propertyName.getStart(), e.propertyName.end)} as ` : ""}${e.name.text} } from ${from};` }))
      : []),
  ];
}

uses

used by