typescripttypescript-compiler-api

Compiler API Typescript. Multiline NamedImports


Try to do a multiline NamedImports.

My code:

const importClause = factory?.createImportClause(
    Boolean(node.importClause?.isTypeOnly),
    node.importClause?.name,
    factory?.createNamedImports(uniqImports as ImportSpecifier[]),
);
const importProps: ts.ImportDeclaration = factory?.createImportDeclaration(
    node.decorators,
    node.modifiers,
    importClause,
    node.moduleSpecifier,
    node.assertClause,
);

my result:

import { One, Two } from 'something';

expected result:

import {
    One,
    Two,
} from 'something';

What should I do?


Solution

  • The printer (emitter) in TypeScript emits named imports and exports without multiline in the source code. You can see that here:

    1. https://github.com/microsoft/TypeScript/blob/8efa88f180eed88b197c509134d60a6313e8f1fd/src/compiler/types.ts#L9069
    2. https://github.com/microsoft/TypeScript/blob/8efa88f180eed88b197c509134d60a6313e8f1fd/src/compiler/emitter.ts#L3570
    3. https://github.com/microsoft/TypeScript/blob/8efa88f180eed88b197c509134d60a6313e8f1fd/src/compiler/emitter.ts#L4412

    From my reading of the source code, I don't see any way to make these multi-line.

    Remember that the printer is not designed for modifying code to be maintained, but moreso for outputting code to be consumed so the output is not very flexible. Depending on the situation, you'll probably have better luck by not using the transformation apis/printer and instead making edits to the source file text directly.