使用打字稿编译器以编程方式生成导入语句 API
Generate import statement programmatically using typescript compiler API
我想生成以下导入语句:
import { Something } from 'a-module';
为此,我使用 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";
如何将花括号语法添加到导入语句中?可能与 createImportClause
中的 namedBindings
参数有关,但我不确定如何使用它。
好的找到了(我猜必须使用 namedBindings
):
// [...]
const importNode = ts.createImportDeclaration(
/* decorators */ undefined,
/* modifiers */ undefined,
ts.createImportClause(
undefined,
ts.createNamedImports(
[
ts.createImportSpecifier(undefined, ts.createIdentifier('Something')),
]
)
),
ts.createLiteral('a-module')
);
// [...]
我想生成以下导入语句:
import { Something } from 'a-module';
为此,我使用 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";
如何将花括号语法添加到导入语句中?可能与 createImportClause
中的 namedBindings
参数有关,但我不确定如何使用它。
好的找到了(我猜必须使用 namedBindings
):
// [...]
const importNode = ts.createImportDeclaration(
/* decorators */ undefined,
/* modifiers */ undefined,
ts.createImportClause(
undefined,
ts.createNamedImports(
[
ts.createImportSpecifier(undefined, ts.createIdentifier('Something')),
]
)
),
ts.createLiteral('a-module')
);
// [...]