我想生成以下import语句:
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";
如何将大括号语法添加到import语句中?可能与createImportClause
中的namedBindings
参数有关,但我不确定如何使用它。
发布于 2020-01-11 11:44:36
Ok找到了(我猜一定是用了namedBindings
):
// [...]
const importNode = ts.createImportDeclaration(
/* decorators */ undefined,
/* modifiers */ undefined,
ts.createImportClause(
undefined,
ts.createNamedImports(
[
ts.createImportSpecifier(undefined, ts.createIdentifier('Something')),
]
)
),
ts.createLiteral('a-module')
);
// [...]
https://stackoverflow.com/questions/59693819
复制相似问题