Skip to content

Instantly share code, notes, and snippets.

@jnwng
Last active September 21, 2015 19:47
Show Gist options
  • Save jnwng/f826203fe700b31d09e1 to your computer and use it in GitHub Desktop.
Save jnwng/f826203fe700b31d09e1 to your computer and use it in GitHub Desktop.
Unwrapping Require.JS style AMD declarations.
module.exports = function(file, api) {
const j = api.jscodeshift;
const makeModuleExports = (objExpr) => {
return j.assignmentExpression(
'=',
j.memberExpression(
j.identifier('module'),
j.identifier('exports')
),
objExpr
);
};
const root = j(file.source);
// define({foo: true}) -> module.exports = {foo: true};
root
.find(j.CallExpression, {callee: {name: 'define'}})
.filter(p => {
return j.ObjectExpression.check(p.value.arguments[0]);
})
.forEach(p => {
j(p).replaceWith(makeModuleExports(p.value.arguments[0]));
});
// define(function() { return foo }) -> module.exports = foo;
root
.find(j.CallExpression, {callee: {name: 'define'}})
.filter(p => {
return j.FunctionExpression.check(p.value.arguments[0]);
})
.forEach(p => {
j(p.value.arguments[0])
.find(j.ReturnStatement)
.forEach(_p => {
_p.replace(
j.expressionStatement(
makeModuleExports(_p.value.argument)
)
);
});
const funcBody = p.value.arguments[0].body.body;
funcBody.forEach(statement => {
root.__paths[0].value.program.body.push(statement);
});
j(p).remove();
});
return root.toSource({quote: 'single'});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment