Search code examples
typescriptabstract-syntax-tree

Generate import statement programmatically using typescript compiler API


I would like to generate the following import statement:

import { Something } from 'a-module';

To do so I am using typescript compiler API:

import * as ts from 'typescript';

const sourceFile = ts.createSourceFile(
    `source.ts`,
    ``,
    ts.ScriptTarget.Latest,
    false,
    ts.ScriptKind.TS
);

const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

const importNode = ts.createImportDeclaration(
    /* decorators */ undefined,
    /* modifiers */ undefined,
    ts.createImportClause(
        ts.createIdentifier('Something'),
        /* namedBindings */ undefined
    ),
    ts.createLiteral('a-module')
);

const result = printer.printNode(ts.EmitHint.Unspecified, importNode, sourceFile);

console.log(result);
// prints --> import Something from "a-module";

How can I add the curly braces syntax to the import statement? Could be something related to namedBindings parameter in createImportClause but I'm not sure how to use it.


Solution

  • Ok found it (as I guessed one must use namedBindings):

    // [...]
    
    const importNode = ts.createImportDeclaration(
        /* decorators */ undefined,
        /* modifiers */ undefined,
        ts.createImportClause(
            undefined,
            ts.createNamedImports(
                [
                    ts.createImportSpecifier(undefined, ts.createIdentifier('Something')),
                ]
            )
        ),
        ts.createLiteral('a-module')
    );
    
    // [...]