Skip to content

Instantly share code, notes, and snippets.

@thekip
Last active November 1, 2020 00:13
Show Gist options
  • Save thekip/bd562299d4f5933c1bff7b08f75a68a8 to your computer and use it in GitHub Desktop.
Save thekip/bd562299d4f5933c1bff7b08f75a68a8 to your computer and use it in GitHub Desktop.
jscodeshift codemod to remove IIFE wrap
module.exports = function(fileInfo, { jscodeshift: j }) {
const ast = j(fileInfo.source);
const body = ast.find(j.Program).get("body");
const getFirstNode = () => ast.find(j.Program).get('body', 0).node;
// Save the comments attached to the first node
const firstNode = getFirstNode();
const { comments } = firstNode;
ast
.find(j.ExpressionStatement, isIifeExpression)
.forEach(ast => {
if (ast.scope.isGlobal) {
j(ast).replaceWith(ast.node.expression.callee.body.body);
}
});
ast // remove 'use strict'
.find(j.ExpressionStatement, isUseStrictExpression)
.forEach(ast => j(ast).remove());
ast //remove global return expressions (which appears after unwrapping from IIFE)
.find(j.ReturnStatement)
.forEach(ast => {
if (ast.scope.isGlobal) {
j(ast).remove();
}
});
// If the first node has been modified or deleted, reattach the comments
const firstNode2 = getFirstNode();
if (firstNode2 !== firstNode) {
firstNode2.comments = comments;
}
return ast.toSource({
arrowParensAlways: true,
quote: "single"
});
};
function isIifeExpression(node) {
return node.expression &&
node.expression.type === "CallExpression" &&
node.expression.callee.type === "FunctionExpression";
}
function isUseStrictExpression(node) {
return (
node.type === "ExpressionStatement" && node.expression && node.expression.value === "use strict"
);
}
@richie50
Copy link

richie50 commented Nov 1, 2020

How do you feed this a list of js files. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment