Skip to content

Instantly share code, notes, and snippets.

@kasperlewau
Created June 9, 2016 13:12
Show Gist options
  • Select an option

  • Save kasperlewau/569db8c3ab1dd358318bf90fc98fc75c to your computer and use it in GitHub Desktop.

Select an option

Save kasperlewau/569db8c3ab1dd358318bf90fc98fc75c to your computer and use it in GitHub Desktop.
primitive AST modifier for export default function + class declaration
exports.onHandleAST = function (ev) {
/**
* The topmost body of the given AST.
*/
var outerBody = ev.data.ast.body;
/**
* If the file is empty, return early.
*/
if (outerBody.length === 0) {
return;
}
/**
* Get the toplevel types.
*/
var outerTypes = outerBody.map(function (t) { return t.type; });
/**
* Find the index of the export default declaration.
*/
var exportDefIdx = outerTypes.indexOf('ExportDefaultDeclaration');
/**
* If there is a ExportDefaultDeclaration in the outer body.
*/
if (exportDefIdx > -1) {
var exportBody = outerBody[exportDefIdx];
var comment = exportBody.leadingComments[0].value;
/**
* If there's an @ngClassLift comment preceding the ExportDefaultDeclaration.
*/
if (/@ngClassLift/gi.test(comment)) {
var innerBody = exportBody.declaration.body.body;
var innerTypes = innerBody.map(function (it) { return it.type; });
var classDeclarationIdx = innerTypes.indexOf('ClassDeclaration');
/**
* If there is a ClassDeclaration inside the ExportDefaultDeclaration body.
*/
if (classDeclarationIdx > -1) {
var classDeclaration = innerBody[classDeclarationIdx];
/**
* Move the ClassDeclaration to the top level,
* and remove it from the ExportDefaultDeclaration.
*/
outerBody.unshift(classDeclaration);
innerBody.splice(classDeclarationIdx, 1);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment