【发布时间】:2021-05-28 01:36:54
【问题描述】:
我使用来自 typescript 编译器 api 的 transform 函数来更改我的代码。
这个函数是递归的,访问每个节点。
当我找到foo 的StringLiteral 时,我想添加foo 来导入my-lib,如下所示:
import { foo } from 'my-lib';
代码可能已经从 my-lib 导入了其他内容,例如:
import { bar } from 'my-lib';
我想避免这种结果(重复导入):
import { foo } from 'my-lib';
import { bar } from 'my-lib';
我能找到的最接近的解决方案是:
const file = (node as ts.Node) as ts.SourceFile;
const update = ts.updateSourceFileNode(file, [
ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(
undefined,
ts.createNamedImports([ts.createImportSpecifier(ts.createIdentifier("default"), ts.createIdentifier("salami"))])
),
ts.createLiteral('salami')
),
...file.statements
]);
但这些功能已被弃用。我不能返回ts.createImportDeclaration,因为我会得到import而不是foo的StringLiteral的代码。
是否有函数说“从 x 更新或插入 y 到导入语句”?
到目前为止我能做的代码:
import * as ts from "typescript";
const code = `
console.log('foo');
`;
const node = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
export const upsertImport = (context) => (rootNode) => {
const { factory } = context;
function visit(node) {
if (ts.isStringLiteral(node) && node.text === "foo") {
// need to add: import { foo } from 'my-lib'; but how??
console.log("need to add: import { foo } from my-lib; but how??");
}
return ts.visitEachChild(node, visit, context);
}
return ts.visitNode(rootNode, visit);
};
const result = ts.transform(node, [upsertImport]);
const transformedSourceFile = result.transformed[0];
const out = printer.printFile(transformedSourceFile);
console.log({ out });
【问题讨论】:
标签: typescript abstract-syntax-tree