Skip to content

Instantly share code, notes, and snippets.

@olvnikon
Created October 6, 2017 11:24
Show Gist options
  • Save olvnikon/66cf8d81ad635e623b77af4fb1d0eee5 to your computer and use it in GitHub Desktop.
Save olvnikon/66cf8d81ad635e623b77af4fb1d0eee5 to your computer and use it in GitHub Desktop.
[AST + JSShiftCode] - "function name" to "window.name = function"
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();
};
@olvnikon
Copy link
Author

olvnikon commented Oct 6, 2017

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() {};

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