Skip to content

Instantly share code, notes, and snippets.

@cletusw
Created August 16, 2017 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cletusw/14324a4c3bf320abaab9fee68c912ab9 to your computer and use it in GitHub Desktop.
Save cletusw/14324a4c3bf320abaab9fee68c912ab9 to your computer and use it in GitHub Desktop.
A codemod to transform amd style includes into commonjs includes
/**
* Modified from https://github.com/skratchdot/amd-to-commonjs-codemod
*/
const buildRequire = (j, v, r) => {
let code = "";
if (v && v.type === "Identifier" && v.name.length) {
code += `const ${v.name}`;
}
if (r && r.type === "Literal" && r.value.length) {
if (code.length) {
code += " = ";
}
code += `require('${r.value}')`;
}
code += ";";
if (code === ";") {
code = "";
}
return code;
};
module.exports = function(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.CallExpression)
.filter(
path =>
path.parentPath.parentPath.node.type === "Program" &&
path.parentPath.node.type === "ExpressionStatement" &&
path.node.type === "CallExpression" &&
path.node.callee.type === "Identifier" &&
path.node.callee.name === "define" &&
path.node.arguments.length === 2 &&
path.node.arguments[0].type === "ArrayExpression" &&
["FunctionExpression", "ArrowFunctionExpression"].indexOf(path.node.arguments[1].type) >= 0
)
.replaceWith(path => {
const arrayExpression = path.node.arguments[0];
const functionExpression = path.node.arguments[1];
const comments = path.node.comments;
const result = [];
const statementSize = Math.max(functionExpression.params.length, arrayExpression.elements.length);
for (let i = 0; i < statementSize; i++) {
result.push(buildRequire(j, functionExpression.params[i], arrayExpression.elements[i]));
}
let spliceIndex = functionExpression.body.body.findIndex(
bodyNode => bodyNode.type !== "ExpressionStatement" || bodyNode.expression.type !== "Literal"
);
functionExpression.body.body.splice(spliceIndex, 0, ...result);
functionExpression.params = [];
var returnValue;
if (functionExpression.body.body.some(bodyNode => bodyNode.type === "ReturnStatement")) {
returnValue = j.assignmentExpression(
"=",
j.memberExpression(j.identifier("module"), j.identifier("exports")),
j.callExpression(functionExpression, [])
);
} else {
returnValue = j.callExpression(functionExpression, []);
}
returnValue.comments = path.node.comments;
return returnValue;
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment