Created
October 6, 2017 11:24
-
-
Save olvnikon/66cf8d81ad635e623b77af4fb1d0eee5 to your computer and use it in GitHub Desktop.
[AST + JSShiftCode] - "function name" to "window.name = function"
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
function isOnTheBody(path) { | |
return path.scope.parent.isGlobal; | |
} | |
function transform(j, path) { | |
const propName = path.value.id.name; | |
const params = path.value.params; | |
const body = path.value.body; | |
j(path).replaceWith( | |
j.expressionStatement( | |
j.assignmentExpression( | |
"=", | |
j.memberExpression( | |
j.identifier("window"), | |
j.identifier(propName) | |
), | |
j.functionExpression( | |
j.identifier(propName), | |
params, | |
body | |
) | |
) | |
) | |
); | |
} | |
module.exports = function(fileInfo, api, options) { | |
const j = api.jscodeshift; | |
const ast = j(fileInfo.source); | |
ast | |
.find(j.FunctionDeclaration) | |
.filter(isOnTheBody) | |
.forEach((path, index) => { | |
transform(j, path); | |
}); | |
return ast.toSource(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you have old libraries with functions on the top of the file you will have problems with bundling them by Webpack. This script transforms functions to variables on the window.
Before:
function a() {}
After:
window.a = function a() {};