Last active
November 1, 2020 00:13
-
-
Save thekip/bd562299d4f5933c1bff7b08f75a68a8 to your computer and use it in GitHub Desktop.
jscodeshift codemod to remove IIFE wrap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you feed this a list of js files. Thanks