此编译时转换器从元素和命名导入中删除装饰器。
我会不断更新代码,因为它只是一个(工作)测试。
export default (decorators: string[]) => {
const importDeclarationsToRemove = [] as ts.ImportDeclaration[];
const updateNamedImports = (node: ts.NamedImports) => {
const newElements = node.elements.filter(v => !decorators.includes(v.name.getText()));
if (newElements.length > 0) {
ts.updateNamedImports(node, newElements);
} else {
importDeclarationsToRemove.push(node.parent.parent);
}
};
const createVisitor = (
context: ts.TransformationContext
): ((node: ts.Node) => ts.VisitResult<ts.Node>) => {
const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult<any> => {
// Remove Decorators from imports
if (ts.isNamedImports(node)) {
updateNamedImports(node);
}
// Remove Decorators applied to elements
if (ts.isDecorator(node)) {
const decorator = node as ts.Decorator;
const identifier = decorator.getChildAt(1) as ts.Identifier;
if (decorators.includes(identifier.getText())) {
return undefined;
}
}
const resultNode = ts.visitEachChild(node, visitor, context);
const index = importDeclarationsToRemove.findIndex(id => id === resultNode);
if (index !== -1) {
importDeclarationsToRemove.splice(index, 1);
return undefined;
}
return resultNode;
};
return visitor;
};
return (context: ts.TransformationContext) => (sourceFile: ts.SourceFile) =>
sourceFile.fileName.endsWith('component.ts')
? ts.visitNode(sourceFile, createVisitor(context))
: sourceFile;
};
program.emit(
program.getSourceFile('test.component.ts'),
undefined,
undefined,
undefined,
{
before: [stripDecorators(['Stateful', 'StatefulTwo', 'StatefulThree'])]
}
);
输入:
import { Stateful, StatefulThree, StatefulTwo } from './decorators';
@Stateful
@StatefulTwo
@StatefulThree
export class Example {
private str = '';
getStr(): string {
return this.str;
}
}
JS 输出:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Example {
constructor() {
this.str = '';
}
getStr() {
return this.str;
}
}
exports.Example = Example;