abstrakt syntaxträd - Generera import-sats programmässigt med TypeScript-kompilator-API


Jag skulle vilja generera följande import-sats:

import { Something } from 'a-module';

För att göra detta använder jag TypeScript-kompilator-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";

Hur kan jag lägga till syntaxen med måsvingar i import-satsen? Det kan vara relaterat till namedBindings-parametern i createImportClause men jag är inte säker på hur man använder den.

Svar #1

Okej, hittade det (som jag gissade måste man använda namedBindings):

// [...]

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

// [...]

Svar #2

lite uppdaterad version av @revys svar ifall någon hittar detta

const { factory } = ts; // or context
const importNode = factory.createImportDeclaration(
    /* modifiers */ undefined,
    factory.createImportClause(
        /* isTypeOnly */ false,
        /* name (default import) */ undefined,
        factory.createNamedImports([
            /* isTypeOnly */ false,
            /* propertyName, inclusion would lead to 'Something as ' */ undefined,
            factory.createImportSpecifier(undefined, ts.createIdentifier('Something')),
        ])
    ),
    factory.createLiteral('a-module')
);

resulterar i

import { Something } from "a-module";

och notera att för att få en filvägsimport, vill du använda createStringLiteral, till exempel.

factory.createStringLiteral('some/file/path')

blir

import { Something } from "some/file/path";

Relaterade artiklar